-
Notifications
You must be signed in to change notification settings - Fork 8
/
ScanFoldFunctions.py
1094 lines (947 loc) · 41.1 KB
/
ScanFoldFunctions.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
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
import subprocess
import random
import re
from multiprocessing import get_context
import os
import statistics
import sys
sys.path.append('/work/LAS/wmoss-lab/ViennaRNA/lib/python3.6/site-packages/')
sys.path.append('/usr/local/lib/python3.6/site-packages')
sys.path.append('/usr/local/lib/python3.9/site-packages/')
import RNA
#import RNAstructure
import multiprocessing
import numpy as np
from random import randint
#from libsvm.svmutil import *
class NucZscore:
#Nucleotide class; defines a nucleotide with a coordinate and a A,T,G,C,U
def __init__(self, nucleotide, coordinate):
self.nucleotide = nucleotide
self.coordinate = coordinate
def add_zscore(self, zscore):
self.zscores.append(zscore)
def add_pair(self, pair):
self.pair.append(pair)
class NucPair:
#Class to define a base pair
def __init__(self, inucleotide, icoordinate, jnucleotide, jcoordinate, zscore, mfe, ed):
self.inucleotide = inucleotide
self.icoordinate = icoordinate
self.jnucleotide = jnucleotide
self.jcoordinate = jcoordinate
self.zscore = zscore
self.mfe = mfe
self.ed = ed
class NucStructure:
#Class to define a base pair
def __init__(self, bond_order, coordinate, nucleotide, structure):
self.bond_order = bond_order
self.coordinate = coordinate
self.nucleotide = nucleotide
self.structure = structure
class NucStructureCount:
#Class to define a base pair
def __init__(self, structure_count, coordinate, nucleotide, structure):
self.structure_count = structure_count
self.coordinate = coordinate
self.nucleotide = nucleotide
self.structure = structure
class ExtractedStructure:
def __init__(self, structure_count, sequence, structure, i, j):
self.structure_count = structure_count
self.sequence = sequence
self.structure = structure
self.i = i
self.j = j
def makedbn(ctfile, name):
icoord = ()
jcoord = ()
kcoord = ()
lcoord = ()
ctfullname = ctfile+".ct"
dbnfullname = ctfile+".dbn"
sequence = ""
with open(ctfullname,'r') as ct1:
dot = ""
data = ct1.readlines()[1:]
for line in data:
rows = line.split()
icoord = int(rows[0])
jcoord = int(rows[-2])
if len(rows[1]) > 1:
print("skipping header")
continue
elif int(rows[-2]) == 0:
dot += '.'
sequence += rows[1]
else:
sequence += rows[1]
if icoord < jcoord:
with open(ctfullname,'r') as ct2:
data = ct2.readlines()
for line in data[icoord:]:
rows = line.split()
kcoord = int(rows[0])
lcoord = int(rows[-2])
if kcoord == jcoord:
#print(kcoord, icoord, "(")
dot += '('
break
else:
if lcoord == 0:
pass
elif lcoord < icoord:
#print('Non-nested pair found: '+str(lcoord)+' to '+str(kcoord))
dot += '<'
break
else:
pass
elif icoord > jcoord:
with open(ctfullname,'r') as ct2:
data = ct2.readlines()
for line in data[jcoord:]:
rows = line.split()
kcoord = int(rows[0])
lcoord = int(rows[-2])
if kcoord == icoord:
#print(kcoord, icoord, ")")
dot += ')'
break
else:
if lcoord == 0:
pass
elif lcoord < jcoord:
dot += '>'
break
else:
pass
else:
print('Error in non-nested pair search'+'\n'+'i = '+str(icoord)+'\n'+'j = '+str(jcoord)+'\n'+'k = '+str(kcoord)+'\n'+'l = '+str(lcoord))
#print(sequence)
#print(dot)
with open(dbnfullname,'w') as dbn:
dbn.writelines(f">{name}\n")
dbn.writelines(f"{sequence}\n")
dbn.writelines(f"{dot}\n")
def multiprocessing(func, args,
workers):
with ProcessPoolExecutor(workers) as ex:
res = ex.map(func, args)
return list(res)
#### Defining Dinucleotide function #####
# Taken from
# altschulEriksonDinuclShuffle.py
# P. Clote, Oct 2003
# NOTE: One cannot use function "count(s,word)" to count the number
# of occurrences of dinucleotide word in string s, since the built-in
# function counts only nonoverlapping words, presumably in a left to
# right fashion.
def computeCountAndLists(s):
#WARNING: Use of function count(s,'UU') returns 1 on word UUU
#since it apparently counts only nonoverlapping words UU
#For this reason, we work with the indices.
#Initialize lists and mono- and dinucleotide dictionaries
List = {} #List is a dictionary of lists
List['A'] = []; List['C'] = [];
List['G'] = []; List['U'] = [];
nuclList = ["A","C","G","U"]
s = s.upper()
s = s.replace("T","U")
nuclCnt = {} #empty dictionary
dinuclCnt = {} #empty dictionary
for x in nuclList:
nuclCnt[x]=0
dinuclCnt[x]={}
for y in nuclList:
dinuclCnt[x][y]=0
#Compute count and lists
nuclCnt[s[0]] = 1
nuclTotal = 1
dinuclTotal = 0
for i in range(len(s)-1):
x = s[i]; y = s[i+1]
List[x].append( y )
nuclCnt[y] += 1; nuclTotal += 1
dinuclCnt[x][y] += 1; dinuclTotal += 1
assert (nuclTotal==len(s))
assert (dinuclTotal==len(s)-1)
return nuclCnt,dinuclCnt,List
def chooseEdge(x,dinuclCnt):
numInList = 0
for y in ['A','C','G','U']:
numInList += dinuclCnt[x][y]
z = random.random()
denom=dinuclCnt[x]['A']+dinuclCnt[x]['C']+dinuclCnt[x]['G']+dinuclCnt[x]['U']
numerator = dinuclCnt[x]['A']
if z < float(numerator)/float(denom):
dinuclCnt[x]['A'] -= 1
return 'A'
numerator += dinuclCnt[x]['C']
if z < float(numerator)/float(denom):
dinuclCnt[x]['C'] -= 1
return 'C'
numerator += dinuclCnt[x]['G']
if z < float(numerator)/float(denom):
dinuclCnt[x]['G'] -= 1
return 'G'
dinuclCnt[x]['U'] -= 1
return 'U'
def connectedToLast(edgeList,nuclList,lastCh):
D = {}
for x in nuclList: D[x]=0
for edge in edgeList:
a = edge[0]; b = edge[1]
if b==lastCh: D[a]=1
for i in range(2):
for edge in edgeList:
a = edge[0]; b = edge[1]
if D[b]==1: D[a]=1
ok = 0
for x in nuclList:
if x!=lastCh and D[x]==0: return 0
return 1
def eulerian(s):
nuclCnt,dinuclCnt,List = computeCountAndLists(s)
#compute nucleotides appearing in s
nuclList = []
for x in ["A","C","G","U"]:
if x in s: nuclList.append(x)
#compute numInList[x] = number of dinucleotides beginning with x
numInList = {}
for x in nuclList:
numInList[x]=0
for y in nuclList:
numInList[x] += dinuclCnt[x][y]
#create dinucleotide shuffle L
firstCh = s[0] #start with first letter of s
lastCh = s[-1]
edgeList = []
for x in nuclList:
if x!= lastCh: edgeList.append( [x,chooseEdge(x,dinuclCnt)] )
ok = connectedToLast(edgeList,nuclList,lastCh)
return ok,edgeList,nuclList,lastCh
def shuffleEdgeList(L):
n = len(L); barrier = n
for i in range(n-1):
z = int(random.random() * barrier)
tmp = L[z]
L[z]= L[barrier-1]
L[barrier-1] = tmp
barrier -= 1
return L
def dinuclShuffle(s):
ok = 0
while not ok:
ok,edgeList,nuclList,lastCh = eulerian(s)
nuclCnt,dinuclCnt,List = computeCountAndLists(s)
#remove last edges from each vertex list, shuffle, then add back
#the removed edges at end of vertex lists.
for [x,y] in edgeList: List[x].remove(y)
for x in nuclList: shuffleEdgeList(List[x])
for [x,y] in edgeList: List[x].append(y)
#construct the eulerian path
L = [s[0]]; prevCh = s[0]
for i in range(len(s)-2):
ch = List[prevCh][0]
L.append( ch )
del List[prevCh][0]
prevCh = ch
L.append(s[-1])
# print(L)
t = "".join(L)
return t
#### Defining my functions #####
def reverse_complement(dna):
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'U': 'A', 'A': 'U'}
return ''.join([complement[base] for base in dna[::-1]])
def NucleotideDictionary (lines):
"""
Function to generate nucleotide dictionary where each key is the i
coordinate of the nucleotide of the input sequence, and each value is a
NucZscore class object (which contains the coordinate and nucleotide
informations)
"""
nuc_dict = {}
for row in lines:
if not row.strip():
continue
else:
i = 1
try:
data = row.split('\t')
#print(data)
icoordinate = data[0]
#print(str(data[7]))
#print(str(data[8]))
# if "A" or "G" or "C" or "T" or "U" or "a" or "g" or "c" or "t" or "u" in list(data[8]):
# print("8"+str(data[8]))
# sequence = transcribe(str(data[8]))
# if "A" or "G" or "C" or "T" or "U" or "a" or "g" or "c" or "t" or "u" in str(data[7]):
# print("7")
sequence = simple_transcribe(str(data[7]))
#print(sequence)
# else:
# raise("Could not find sequence for window")
except:
#print("Comma separated")
data = row.split(',')
strand = int(data[11])
#print(strand)
icoordinate = data[0]
if "A" or "G" or "C" or "T" or "U" or "a" or "g" or "c" or "t" or "u" in str(data[8]):
sequence_raw = simple_transcribe(str(data[8]))
elif "A" or "G" or "C" or "T" or "U" or "a" or "g" or "c" or "t" or "u" in str(data[7]):
sequence_raw = simple_transcribe(str(data[7]))
else:
raise("Could not find sequence for window")
#print(sequence_raw)
if strand == -1:
#print("NegStrand")
sequence = sequence_raw[::-1]
#print(sequence)
else:
#print("PosStrand")
sequence = sequence_raw
for nuc in sequence:
x = NucZscore(nuc,(int(icoordinate)+int(i)-1))
nuc_dict[x.coordinate] = x
i += 1
return nuc_dict;
def competing_pairs(bp_dict, coordinate):
#Function to determine other i-nuc which compete for the same j-nuc
comp_pairs = {}
i = 0
for k, v in bp_dict.items():
if ((int(v.jcoordinate) == int(coordinate)) or
(int(v.icoordinate) == int(coordinate))):
x = NucPair(v.inucleotide, v.icoordinate, v.jnucleotide,
v.jcoordinate, v.zscore, v.mfe, v.ed)
comp_pairs[i] = x
i += 1
else:
continue
return comp_pairs;
def best_basepair(bp_dict, nucleotide, coordinate, type):
#Function to define best i-j pair for i-nucleotide
zscore_dict = {}
pair_dict = {}
partner_key = 0
for k, pair in sorted(bp_dict.items()):
if int(pair.icoordinate) < int(pair.jcoordinate):
#print("148")
x = NucPair(pair.inucleotide, pair.icoordinate, pair.jnucleotide,
pair.jcoordinate, pair.zscore, pair.mfe, pair.ed)
try:
y = zscore_dict[partner_key]
y.append(pair.zscore)
z = pair_dict[partner_key]
z.append(x)
except:
zscore_dict[partner_key] = []
y = zscore_dict[partner_key]
y.append(pair.zscore)
pair_dict[partner_key] = []
z = pair_dict[partner_key]
z.append(x)
sum_z = {}
for k1, v1 in zscore_dict.items():
sum_z[k1] = sum(v1)
test = sum_z[k1] = sum(v1)
mean_z = {}
for k1, v1 in zscore_dict.items():
mean_z[k1] = statistics.mean(v1)
test = mean_z[k1] = statistics.mean(v1)
partner_key += 1
elif int(pair.icoordinate) > int(pair.jcoordinate):
x = NucPair(pair.inucleotide, pair.icoordinate, pair.jnucleotide,
pair.jcoordinate, pair.zscore, pair.mfe, pair.ed)
try:
y = zscore_dict[partner_key]
y.append(pair.zscore)
z = pair_dict[partner_key]
z.append(x)
except:
zscore_dict[partner_key] = []
y = zscore_dict[partner_key]
y.append(pair.zscore)
pair_dict[partner_key] = []
z = pair_dict[partner_key]
z.append(x)
sum_z = {}
for k1, v1 in zscore_dict.items():
sum_z[k1] = sum(v1)
test = sum_z[k1] = sum(v1)
mean_z = {}
for k1, v1 in zscore_dict.items():
mean_z[k1] = statistics.mean(v1)
test = mean_z[k1] = statistics.mean(v1)
partner_key += 1
elif int(pair.icoordinate) == int(pair.jcoordinate):
#print("210")
x = NucPair(pair.inucleotide, pair.icoordinate, pair.jnucleotide,
pair.jcoordinate, pair.zscore, pair.mfe, pair.ed)
try:
y = zscore_dict[partner_key]
y.append(pair.zscore)
z = pair_dict[partner_key]
z.append(x)
except:
zscore_dict[partner_key] = []
y = zscore_dict[partner_key]
y.append(pair.zscore)
pair_dict[partner_key] = []
z = pair_dict[partner_key]
z.append(x)
sum_z = {}
for k1, v1 in zscore_dict.items():
sum_z[k1] = sum(v1)
test = sum_z[k1] = sum(v1)
mean_z = {}
for k1, v1 in zscore_dict.items():
mean_z[k1] = statistics.mean(v1)
test = mean_z[k1] = statistics.mean(v1)
partner_key += 1
else:
print("FAIL")
best_bp = NucPair(pair.inucleotide, pair.icoordinate,
pair.jnucleotide, pair.jcoordinate, pair.zscore)
partner_key += 1
if type == 'sum':
best_bp_key = min(sum_z, key = sum_z.get)
if type == 'mean':
best_bp_key = min(mean_z, key = mean_z.get)
try:
v = pair_dict[best_bp_key]
best_bp = v[0]
except:
print("ERROR")
print(k)
return best_bp;
def write_ct(base_pair_dictionary, filename, filter, strand, name, start_coordinate):
#Function to write connectivity table files from a list of best i-j pairs
w = open(filename, 'w')
w.write((str(len(base_pair_dictionary))+"\t"+name+"\n"))
if strand == 1:
for k, v in base_pair_dictionary.items():
#print(start_coordinate)
#print(v.icoordinate)
icoordinate = str(int(v.icoordinate)-int(int(start_coordinate)-1))
#print(icoordinate)
jcoordinate = str(int(v.jcoordinate)-int(int(start_coordinate)-1))
#print(jcoordinate)
key_coordinate = str(int(k)-int(start_coordinate)+1)
#print(key_coordinate)
if float(v.zscore) < filter:
if ((int(icoordinate) < int(jcoordinate)) and (int(icoordinate) == int(key_coordinate))): #test to see if reverse bp.
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.inucleotide, int(key_coordinate)-1, int(key_coordinate)+1, int(jcoordinate), int(key_coordinate)))
elif ((int(icoordinate) > int(jcoordinate)) and (int(icoordinate) == int(key_coordinate))): #test to see if reverse bp.
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.inucleotide, int(key_coordinate)-1, int(key_coordinate)+1, int(jcoordinate), int(key_coordinate)))
elif (int(icoordinate) < int(jcoordinate)) and (int(key_coordinate) == int(jcoordinate)):
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.jnucleotide, int(key_coordinate)-1, int(key_coordinate)+1, int(icoordinate), int(key_coordinate)))
elif (int(icoordinate) > int(jcoordinate)) and (int(key_coordinate) == int(jcoordinate)):
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.jnucleotide, int(key_coordinate)-1, int(key_coordinate)+1, int(icoordinate), int(key_coordinate)))
elif int(icoordinate) == int(jcoordinate):
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.inucleotide, int(key_coordinate)-1, int(key_coordinate)+1, 0, int(key_coordinate)))
#
# elif (int(key_coordinate) != icoordinate) and (int(key_coordinate) != int(jcoordinate)):
# continue
# #w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.inucleotide, int(key_coordinate)-1, int(key_coordinate)+1, 0, int(key_coordinate)))
else:
print("Error at", int(key_coordinate), v.inucleotide, icoordinate, v.jnucleotide, int(jcoordinate), v.zscore)
else:
if int(key_coordinate) == int(icoordinate):
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.inucleotide, int(key_coordinate)-1, int(key_coordinate)+1, 0, int(key_coordinate)))
elif int(key_coordinate) == int(jcoordinate):
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.jnucleotide, int(key_coordinate)-1, int(key_coordinate)+1, 0, int(key_coordinate)))
else:
raise ValueError("WriteCT function did not find a nucleotide to match coordinate (i or j coordinate does not match dictionary key_coordinateey_coordinateey)")
continue
if strand == -1:
end_coordinate = len(base_pair_dictionary)
for k, v in sorted(base_pair_dictionary.items(), key=lambda x:x[0], reverse = True):
# print(start_coordinate)
# print(end_coordinate)
# print("i="+str(v.icoordinate))
# print("j="+str(v.jcoordinate))
# print("k="+str(k))
icoordinate = str(int(end_coordinate)+1-(int(int(v.icoordinate))))
# print("i_after"+str(icoordinate))
jcoordinate = str(int(end_coordinate)+1-(int(int(v.jcoordinate))))
# print("j_after="+str(jcoordinate))
key_coordinate = str(int(end_coordinate)-int(k)+1)
# print("key="+str(key_coordinate))
if float(v.zscore) < filter:
if ((int(icoordinate) < int(jcoordinate)) and (int(icoordinate) == int(key_coordinate))): #test to see if reverse bp.
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.inucleotide, int(key_coordinate)-1, int(key_coordinate)+1, int(jcoordinate), int(key_coordinate)))
elif ((int(icoordinate) > int(jcoordinate)) and (int(icoordinate) == int(key_coordinate))): #test to see if reverse bp.
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.inucleotide, int(key_coordinate)-1, int(key_coordinate)+1, int(jcoordinate), int(key_coordinate)))
elif (int(icoordinate) < int(jcoordinate)) and (int(key_coordinate) == int(jcoordinate)):
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.jnucleotide, int(key_coordinate)-1, int(key_coordinate)+1, int(icoordinate), int(key_coordinate)))
elif (int(icoordinate) > int(jcoordinate)) and (int(key_coordinate) == int(jcoordinate)):
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.jnucleotide, int(key_coordinate)-1, int(key_coordinate)+1, int(icoordinate), int(key_coordinate)))
elif int(icoordinate) == int(jcoordinate):
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.inucleotide, int(key_coordinate)-1, int(key_coordinate)+1, 0, int(key_coordinate)))
#
# elif (int(key_coordinate) != icoordinate) and (int(key_coordinate) != int(jcoordinate)):
# continue
# #w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.inucleotide, int(key_coordinate)-1, int(key_coordinate)+1, 0, int(key_coordinate)))
else:
print("Error at", int(key_coordinate), v.inucleotide, icoordinate, v.jnucleotide, int(jcoordinate), v.zscore)
else:
if int(key_coordinate) == int(icoordinate):
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.inucleotide, int(key_coordinate)-1, int(key_coordinate)+1, 0, int(key_coordinate)))
elif int(key_coordinate) == int(jcoordinate):
w.write("%d %s %d %d %d %d\n" % (int(key_coordinate), v.jnucleotide, int(key_coordinate)-1, int(key_coordinate)+1, 0, int(key_coordinate)))
else:
raise ValueError("WriteCT function did not find a nucleotide to match coordinate (i or j coordinate does not match dictionary key_coordinateey_coordinateey)")
continue
def write_dp(base_pair_dictionary, filename, filter, minz):
#this function will create a dp file for IGV
w = open(filename, 'w')
for k, v in base_pair_dictionary.items():
if float(v.zscore) < filter:
#probability = (v.zscore/minz)
if int(v.icoordinate) < int(v.jcoordinate):
#w.write("%d\t%d\t%f\n" % (k, int(v.jcoordinate), float(-(math.log10(probability)))))
w.write("%d\t%d\t%f\n" % (v.icoordinate, int(v.jcoordinate), float(((-1/minz)*(v.zscore)))/minz))
elif int(v.icoordinate) > int(v.jcoordinate):
w.write("%d\t%d\t%f\n" % (int(v.icoordinate), int(v.jcoordinate), float(((-1/minz)*(v.zscore)))/minz))
elif int(v.icoordinate) == int(v.jcoordinate):
w.write("%d\t%d\t%f\n" % (k, int(v.jcoordinate), float(((-1/minz)*(v.zscore)))/minz))
else:
print("Error at:", k)
def simple_transcribe(seq):
#Function to covert T nucleotides to U nucleotides
for ch in seq:
rna_seq = seq.replace('T', 'U')
return(rna_seq)### Use transcribe function via biopython (on .seq type)
def reverse_transcribe(seq):
#Function to covert T nucleotides to U nucleotides
for ch in seq:
rna_seq = seq.replace('U', 'T')
return(rna_seq)
def flip_structure(structure):
#Function to reverse structure in a given window, for negative strand genes
flip = {'(':')', ')':'(', '.':'.'}
return ''.join([flip[pair] for pair in structure[::-1]])
def write_fasta(nucleotide_dictionary, outputfilename, name):
w = open(outputfilename, 'w')
fasta_sequence = str()
for k, v in nucleotide_dictionary.items():
nucleotide = v.nucleotide
fasta_sequence += nucleotide
w.write(">"+name+"\n")
w.write(str(fasta_sequence)+"\n")
def nuc_dict_to_seq(nucleotide_dictionary):
fasta_sequence = str()
for k, v in nucleotide_dictionary.items():
nucleotide = v.nucleotide
#print(nucleotide)
fasta_sequence += nucleotide
return fasta_sequence
def write_wig_dict(nucleotide_dictionary, outputfilename, name, step_size):
w = open(outputfilename, 'w')
#write wig file header
w.write("%s %s %s %s %s\n" % ("fixedStep", "chrom="+name, "start=1", "step="+str(step_size), "span="+str(step_size)))
#write values of zscores
for k, v in nucleotide_dictionary.items():
w.write("%f\n" % (v.zscore))
def write_wig(metric_list, step, name, outputfilename):
w = open(outputfilename, 'w')
w.write("%s %s %s %s %s\n" % ("fixedStep", "chrom="+name, "start=1", "step="+str(step), "span="+str(step)))
for metric in metric_list:
# try:
# float(metric)
# print("GOOD", metric)
# except:
# print(metric)
if metric == "#DIV/0!":
w.write("%s\n" % (metric))
else:
try:
w.write("%f\n" % (metric))
except:
w.write("%s\n" % (metric))
#print(metric)
def write_bp(base_pair_dictionary, filename, start_coordinate, name, minz):
w = open(filename, 'w')
#set color for bp file (igv format)
w.write("%s\t%d\t%d\t%d\t%s\n" % (str("color:"), 55, 129, 255, str("Less than -2 "+str(minz))))
w.write("%s\t%d\t%d\t%d\t%s\n" % (str("color:"), 89, 222, 111, "-1 to -2"))
w.write("%s\t%d\t%d\t%d\t%s\n" % (str("color:"), 236, 236, 136, "0 to -1"))
w.write("%s\t%d\t%d\t%d\t%s\n" % (str("color:"), 199, 199, 199, "0"))
w.write("%s\t%d\t%d\t%d\t%s\n" % (str("color:"), 228, 228, 228, "0 to 1"))
w.write("%s\t%d\t%d\t%d\t%s\n" % (str("color:"), 243, 243, 243, "1 to 2"))
w.write("%s\t%d\t%d\t%d\t%s\n" % (str("color:"), 247, 247, 247, str("Greater than 2")))
i = 0
for k, v in base_pair_dictionary.items():
#choose color
if float(v.zscore) < float(-2):
score = str(0)
#print(k, v.zscore, score)
elif (float(v.zscore) < int(-1)) and (float(v.zscore) >= -2):
score = str(1)
#print(k, v.zscore, score)
elif (float(v.zscore) < int(0)) and (float(v.zscore) >= -1):
score = str(2)
#print(k, v.zscore, score)
elif float(v.zscore) == 0 :
score = str(3)
#print(k, v.zscore, score)
elif 0 < float(v.zscore) <= 1:
score = str(4)
#print(k, v.zscore, score)
elif 1 < float(v.zscore) <= 2:
score = str(5)
#print(k, v.zscore, score)
elif float(v.zscore) > 2:
score = str(6)
#print(k, v.zscore, score)
else:
print(k, v.zscore, score)
score = str(score)
# ensure coordinates to start at 1 to match with converted fasta file
sc = int(int(start_coordinate)-1)
#print(length)
if int(v.icoordinate) < int(v.jcoordinate):
#w.write("%d\t%d\t%f\n" % (k, int(v.jcoordinate), float(-(math.log10(probability)))))
# print(name, int(v.icoordinate), int(v.icoordinate), int(v.jcoordinate), int(v.jcoordinate), score)
# print(name, str(int(v.icoordinate)-sc), str(int(v.icoordinate)-sc), str(int(v.jcoordinate)-sc), str(int(v.jcoordinate)-sc), score)
w.write("%s\t%d\t%d\t%d\t%d\t%s\n" % (name, int(v.icoordinate)-sc, int(v.icoordinate)-sc, int(v.jcoordinate)-sc, int(v.jcoordinate)-sc, score))
elif int(v.icoordinate) > int(v.jcoordinate):
# print(name, int(v.icoordinate), int(v.icoordinate), int(v.jcoordinate), int(v.jcoordinate), score)
# print(name, str(int(v.icoordinate)-sc), str(int(v.icoordinate)-sc), str(int(v.jcoordinate)-sc), str(int(v.jcoordinate)-sc), score)
w.write("%s\t%d\t%d\t%d\t%d\t%s\n" % (name, int(v.icoordinate)-sc, int(v.icoordinate)-sc, int(v.jcoordinate)-sc, int(v.jcoordinate)-sc, score))
elif int(v.icoordinate) == int(v.jcoordinate):
# print(name, int(v.icoordinate), int(v.icoordinate), int(v.jcoordinate), int(v.jcoordinate), score)
# print(name, str(int(v.icoordinate)-sc), str(int(v.icoordinate)-sc), str(int(v.jcoordinate)-sc), str(int(v.jcoordinate)-sc), score)
w.write("%s\t%d\t%d\t%d\t%d\t%s\n" % (name, k-sc, k-sc, int(v.jcoordinate)-sc, int(v.jcoordinate)-sc, score))
else:
print("2 Error at:", k)
def utf8len(s):
return len(s.encode('utf-8'))
def write_fai (nucleotide_dictionary, filename, name):
w = open(filename, 'w')
name = str(name)
length = str(len(nucleotide_dictionary))
offset = str(utf8len(str(">"+name+"\n")))
linebases = str(len(nucleotide_dictionary))
linewidth = str(len(nucleotide_dictionary)+1)
w.write("%s\t%s\t%s\t%s\t%s\n" % (name, length, offset, linebases, linewidth))
###### Function to calculate ZScore on list of MFEs #################
def pvalue_function(energy_list, randomizations):
below_native = 0
total_count = len(energy_list)
native_mfe = float(energy_list[0])
#scrambled_mean_mfe = statistics.mean(energy_list[1:randomizations])
for MFE in energy_list:
if float(MFE) < float(native_mfe):
below_native += 1
pvalue = float(float(below_native) / float(total_count))
return pvalue;
###### Function to calculate ZScore on list of MFEs #################
def zscore_function(energy_list, randomizations):
mean = statistics.mean(energy_list)
sd = statistics.stdev(energy_list)
native_mfe = energy_list[0]
scrambled_mean_mfe = statistics.mean(energy_list[1:randomizations])
#scrambled_sd = statistics.stdev(energy_list[1:randomizations])
if sd != 0:
zscore = (native_mfe - scrambled_mean_mfe)/sd
if sd == 0:
zscore = float(00.00)
return zscore;
def flip_structure(structure):
#Function to reverse structure in a given window, for negative strand genes
flip = {'(':')', ')':'(', '.':'.', '&':'&'}
return ''.join([flip[pair] for pair in structure[::-1]])
def rna_refold(frag, temperature, constraint_file):
args = ["RNAfold", "-p", "-T", str(temperature), '-C', constraint_file]
fc = subprocess.run(args, input=frag, check=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = str(fc.stdout)
test = out.splitlines()
structure = test[2].split()[0]
centroid = test[4].split()[0]
MFE = test[2].split(" ", 1)[1]
try:
MFE = float(re.sub('[()]', '', MFE))
except:
print("Error parsing MFE values", test)
ED = float(test[5].split()[-1])
return (structure, centroid, MFE, ED)
def rna_folder(arg):
(frag, temperature, algo) = arg
md = RNA.md()
md.temperature = int(temperature)
### Not functioning currently
# if algo == "rnastructure":
# p = RNAstructure.RNA.fromString(str(frag))
# p.FoldSingleStrand(mfeonly=True)
# MFE = p.GetFreeEnergy(1)
# #(structure, MFE) = RNA.fold(str(frag))
if algo == "rnafold":
fc = RNA.fold_compound(str(frag), md)
(structure, MFE) = fc.mfe()
return MFE;
# def rna_cofolder(frag1, frag2):
# frag1 = str(frag1)
# frag2 = str(frag2)
# (structure, energy) = RNA.duplex(frag1, frag2)
# #print(md.temperature)
# return energy;
def randomizer(frag):
result = ''.join(random.sample(frag,len(frag)))
return result;
###### Function to calculate MFEs using RNAfold #################
def energies(seq_list, temperature, algo):
energy_list = []
energy_list = multiprocessing(rna_folder, [(sequence, temperature, algo) for sequence in seq_list], 12)
# for sequence in seq_list:
# #fc = RNA.fold_compound(str(sequence))
# (structure, MFE) = RNA.fold(str(sequence)) # calculate and define variables for mfe and structure
# energy_list.append(MFE) # adds the native fragment to list
return energy_list;
###### Function to calculate MFEs using RNAcofold #################
def cofold_energies(frag1, seq_list):
energy_list = []
for sequence in seq_list:
scrambled_frag1 = ''.join(random.sample(frag1,len(frag1)))
#scrambled_frag1 = frag1
#print(scrambled_frag1)
#fc = RNA.fold_compound(str(sequence))
duplex = RNA.duplexfold(str(scrambled_frag1), str(sequence)) # calculate and define variables for mfe and structure
# duplex = RNA.duplexfold(str(frag1), str(sequence)) # calculate and define variables for mfe and structure
MFE = duplex.energy
energy_list.append(MFE) # adds the native fragment to list
return energy_list;
######Function to create X number of scrambled RNAs in list #################
#test
def scramble(text, randomizations, type):
frag = str(text)
frag_seqs = []
if type == "di":
frag = simple_transcribe(frag)
for _ in range(randomizations):
result = dinuclShuffle(frag)
frag_seqs.append(result)
elif type == "mono":
frag_seqs = multiprocessing(randomizer, [frag for i in range(randomizations)], 12)
# for _ in range(int(randomizations)):
# result = ''.join(random.sample(frag,len(frag)))
# frag_seqs.append(result)
else:
print("Shuffle type not properly designated; please input \"di\" or \"mono\"")
return frag_seqs;
def get_structure(rnastructure_object):
structure = []
p = rnastructure_object
for i in range(1, p.GetSequenceLength()+1):
pair = p.GetPair(i)
if pair == 0:
structure.append(".")
elif pair > i:
structure.append("(")
elif pair < i:
structure.append(")")
else:
raise ValueError('"get_structure" funciton error: RNA structure class could not be read to generate folding structure')
return structure;
def findpair(nucdict, k):
#print(k)
base = nucdict[k].coordinate
order = nucdict[k].bond_order
#print(base, nucdict[k].nucleotide)
#print("Finding pair for ", nucdict[k].coordinate, nucdict[k].structure)
if nucdict[k].structure == ".":
print("Cant find pair for unpaired nucleotide at i =", k+1)
if nucdict[k].structure == "(":
i = 1
test = 1
while test > 0:
if nucdict[k+i].structure == ".":
i += 1
if nucdict[k+i].structure == "(":
i += 1
test +=1
if nucdict[k+i].structure == ")":
test -= 1
if test == 0:
#print("FOUND")
pair = nucdict[k+i]
#print(nucdict[k].coordinate, nucdict[k].structure, pair.structure, pair.coordinate)
i += 1
#print(i)
if nucdict[k].structure == ")":
i = 1
test = 1
#print(nucdict[k].coordinate)
while test > 0:
#print(test)
if nucdict[k-i].structure == ".":
i += 1
if nucdict[k-i].structure == ")":
i += 1
test += 1
if nucdict[k-i].structure == "(":
test -= 1
if test == 0:
#print("FOUND")
pair = nucdict[k-i]
#print(test, nucdict[k].coordinate, nucdict[k].structure, pair.structure, pair.coordinate)
i += 1
return pair;
def dbn2ct(dbnfile):
#print("Running dbn2ct")
#Function to write connectivity table files from a list of best i-j pairs
with open(dbnfile, 'r') as f:
lines = f.readlines()
sequence_raw = str(lines[1].strip())
structure_raw = str(lines[2].strip())
sequence = list(sequence_raw)
structure = list(structure_raw)
length = len(sequence)
length_st = len(structure)
bond_order = []
bond_count = 0
nuc_dict = {}
#print(sequence, structure, length)
#Inititate base pair tabulation variables
bond_order = []
bond_count = 0
nuc_dict = {}
#print(length)
if length != length_st:
print(sequence, structure)
raise("ERROR structure and sequence not same length.")
#Iterate through sequence to assign nucleotides to structure type
m = 0
#print(length)
while m <= length-1:
#print(structure[m])
if structure[m] == '(':
# print(m, structure[m])
bond_count += 1
bond_order.append(bond_count)
nuc_dict[m] = NucStructure(bond_count, (m+1), sequence[m], structure[m])
m += 1
elif structure[m] == ')':
# print(m, structure[m])
bond_order.append(bond_count)
bond_count -= 1
nuc_dict[m] = NucStructure(bond_count, (m+1), sequence[m], structure[m])
m += 1
elif str(structure[m]) == ( '.' ):
# print(m, structure[m])
bond_order.append(0)
nuc_dict[m] = NucStructure(bond_count, (m+1), sequence[m], structure[m])
m += 1
elif str(structure[m]) == ( '<' ):
# print(m, structure[m])
bond_order.append(0)
nuc_dict[m] = NucStructure(bond_count, (m+1), sequence[m], structure[m])
m += 1
elif str(structure[m]) == ( '>' ):
# print(m, structure[m])
bond_order.append(0)
nuc_dict[m] = NucStructure(bond_count, (m+1), sequence[m], structure[m])
m += 1
elif str(structure[m]) == ( '{' ):
# print(m, structure[m])
bond_order.append(0)
nuc_dict[m] = NucStructure(bond_count, (m+1), sequence[m], structure[m])
m += 1
elif str(structure[m]) == ( '}' ):
# print(m, structure[m])
bond_order.append(0)
nuc_dict[m] = NucStructure(bond_count, (m+1), sequence[m], structure[m])
m += 1
else:
print("Error", bond_count, (m+1), sequence[m], structure[m])
m += 1
continue
#print("no")
# for k, v in nuc_dict.items():
# print(str(k+1), str(v.bond_order), str(v.nucleotide), str(k), str(k-1), str(k+1), str(0), str(k+1))