-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsource.py
3531 lines (2925 loc) · 121 KB
/
source.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
###this script used to coding pre-miRNA sequences with sequence and structure features
#################################################################
###miRNAInfoList includes: miRNA ID, mature_miRNASeq, ####
###mature_miRNA position in pre-miRNA sequence, ####
###pre-miRNA sequence, and structure ####
#################################################################
##generate dp.ps and ss.ps files for each RNA sequence. Only run once.
##RNAfold -p -d2 --noLP < sequence1.fa > sequence1.out
import sys, os, string, math, random, shutil, glob, re
import numpy as np
from random import randint
from time import sleep
from sklearn.externals import joblib
from decimal import Decimal
from sklearn.cross_validation import cross_val_score
from sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sknn.mlp import Classifier, Layer
from sklearn import svm, tree
from sklearn import cross_validation
from sklearn.metrics import roc_auc_score
from sklearn.feature_selection import chi2, SelectKBest, SelectPercentile, f_classif
from sklearn.ensemble import ExtraTreesClassifier
cv = 10
minCandidateMiRNALen = 16
maxCandidateMiRNALen = 30
minPredScore = 0.25
upOffSet = 5
downOffSet = 5
################################################################################################
#####check OS type##################################################
################################################################################################
def checkOSType():
from sys import platform as _platform
if _platform == "linux" or _platform == "linux2":
return "linux"
elif _platform == "darwin":
return "mac"
elif _platform == "win32":
return "win"
else:
return "undefined OS"
#end fun
##read lines from a file
def readLinesFromFile (fileDir):
fpr = open(fileDir, "r")
lines = fpr.readlines()
fpr.close()
return lines
#end fun
##write lines to a file
def writeLinesToFile( lineList, endFlag, fileDir ):
fpw = open( fileDir, "w" )
for curLine in lineList:
fpw.write( curLine + endFlag )
fpw.close()
#end def
##check file exists
def fileExist(fileDir):
return os.path.exists(fileDir)
#end fun
##remove file
def removeFile(fileDir):
if(fileExist(fileDir) == True):
try:
os.remove(fileDir)
except:
print "Warning: Failed to remove ", fileDir
#end if
#end fun
##move file
def moveFile( curFileDir, destinationFileDir ):
shutil.move(curFileDir, destinationFileDir)
#end def
##extract elements from list
def extactElementsFromList( List, elmentIdx ):
return [List[i] for i in elmentIdx]
#end def
##create file dictionary if not exists
def createDict( fileDic ):
if not os.path.exists( fileDic ):
os.makedirs( fileDic )
#end fun
##remove files in one dictionary
def clearnDict( fileDic ):
r = glob.glob(fileDic + '*')
for i in r:
os.remove(i)
#end fun
##fold pre-miRNAs sequences using RNAfold
def foldPreMiRNASeq( preMiRNADic, RNAfoldDic, tmpFileDir, RNAfoldResDir ):
fpw = open(tmpFileDir, "w")
for curPreMiRNAID in preMiRNADic.keys():
curPreMiRNASeq = preMiRNADic[curPreMiRNAID]
fpw.write(">" + curPreMiRNAID + "\n" + curPreMiRNASeq + "\n" )
#end for
fpw.close()
foldCommand = RNAfoldDic + "RNAfold -p -d2 --noLP < " + tmpFileDir + " > " + RNAfoldResDir
res = os.system(foldCommand)
if( res != 0 ):
print "Error to run RNAfold using the command:", foldCommand
sys.exit()
print "fold pre-miRNA sequences successfully.\n"
#end def
##parse RNAfold result
def parseRNAfoldResult( RNAfoldResDir ):
lines = readLinesFromFile(RNAfoldResDir)
seqNum = len(lines)/6
resDic = {}
for ii in range(seqNum):
if( (6*ii + 5) > len(lines) ):
break
curID = lines[6*ii]
curID = curID[1:]
curID = curID.strip()
curStruct = lines[6*ii+2]
elements = curStruct.split(" ")
resDic[curID] = elements[0]
#end for ii
return resDic
#end fun
##check input data for training
def checkFileForTraining(fileDir, RNAfoldDic, sourceDic, dpSSFileDic, dpSSFlag = True ):
newFileDir = fileDir
lines = readLinesFromFile(fileDir)
preMiRNADic = {}
lenList=[]
for curLine in lines:
elements = curLine.split("\t")
curElementLen = len(elements)
lenList.append(curElementLen)
if( curElementLen != 4 and curElementLen != 5 ):
print curLine
print "Error: format error in the file input for training. For each miRNA per line, there are four or five elements seperated with tab keys, Please check the format:"
print "miRNA_ID\tpre-miRNA_ID\tmiRNA_sequence\tpre-miRNA_sequence"
print "or\n"
print "miRNA_ID\tpre-miRNA_ID\tmiRNA_sequence\tpre-miRNA_sequence\tpre-miRNA_structure\n\n"
sys.exit()
else:
curMiRNAID = elements[0]
curPreMiRNAID = elements[1]
curMiRNASeq = elements[2]
curPreMiRNASeq = elements[3]
if( curPreMiRNAID not in preMiRNADic.keys() ):
preMiRNADic[curPreMiRNAID] = curPreMiRNASeq
#end if
#end else
#end for
print len( preMiRNADic.keys() ), " pre-miRNAs, ", len(lines), " miRNAs included"
##check lenList
lenList = list( set(lenList) )
if( len(lenList) > 1 ):
print "Error: different element number for miRNAs in ", fileDir, " Element number:", lenList
else:
if( lenList[0] == 5 and dpSSFlag == False ):
print "Structure and dp_ss have been given.\n"
else:
#structure required
tmpFileDir = dpSSFileDic + "tmp_seq.txt"
RNAfileResDir = dpSSFileDic + "tmp_struct.txt"
foldPreMiRNASeq(preMiRNADic, RNAfoldDic, tmpFileDir, RNAfileResDir )
structDic = parseRNAfoldResult(RNAfileResDir)
#removeFile(tmpFileDir)
#removeFile(RNAfileResDir)
##copy dp_ps, ss_ps file
if( dpSSFlag == True ):
mvCommand = "mv " + sourceDic + "*_dp.ps " + dpSSFileDic
runCommand(mvCommand)
mvCommand = "mv " + sourceDic + "*_ss.ps " + dpSSFileDic
runCommand(mvCommand)
else:
rmCommand = "rm " + sourceDic + "*_dp.ps " + dpSSFileDic
runCommand(rmCommand)
rmCommand = "rm " + sourceDic + "*_ss.ps " + dpSSFileDic
runCommand(rmCommand)
#end else
#structure are provided
if( lenList[0] == 4 ):
newFileDir = fileDir + "_ref"
fpw = open( newFileDir, "w" )
for curLine in lines:
elements = curLine.split("\t")
curPreMiRNAID = elements[1]
if( curPreMiRNAID not in structDic.keys() ):
continue
curPreMiRNAStruct = structDic[curPreMiRNAID]
fpw.write( curLine.strip() + "\t" + curPreMiRNAStruct + "\n" )
#end for
fpw.close()
#end if
#end else
#end else
return newFileDir
#end def
##check input data for training
def checkFileForPrediction(fileDir, RNAfoldDic, sourceDic, dpSSFileDic, dpSSFlag = True ):
newFileDir = fileDir
lines = readLinesFromFile(fileDir)
preMiRNADic = {}
lenList=[]
for curLine in lines:
elements = curLine.split("\t")
curElementLen = len(elements)
lenList.append(curElementLen)
if( curElementLen != 2 and curElementLen != 3 ):
print curLine
print "Error: format error in the file input for prediction. For each miRNA per line, there are two or three elements seperated with tab keys, Please check the format:"
print "pre-miRNA_ID\tpre-miRNA_sequence"
print "or\n"
print "pre-miRNA_ID\tpre-miRNA_sequence\tpre-miRNA_structure\n\n"
sys.exit()
else:
curPreMiRNAID = elements[0]
curPreMiRNASeq = elements[1]
if( curPreMiRNAID not in preMiRNADic.keys() ):
preMiRNADic[curPreMiRNAID] = curPreMiRNASeq
#end if
#end else
#end for
print len( preMiRNADic.keys() ), " pre-miRNAs for prediction\n"
##check lenList
lenList = list( set(lenList) )
if( len(lenList) > 1 ):
print "Error: different element number for pre-miRNAs in ", fileDir, " Element number:", lenList
else:
if( lenList[0] == 3 and dpSSFlag == False ):
print "Structure and dp_ss have been given.\n"
else:
#structure required
tmpFileDir = dpSSFileDic + "tmp_seq.txt"
RNAfileResDir = dpSSFileDic + "tmp_struct.txt"
foldPreMiRNASeq(preMiRNADic, RNAfoldDic, tmpFileDir, RNAfileResDir )
structDic = parseRNAfoldResult(RNAfileResDir)
#removeFile(tmpFileDir)
#removeFile(RNAfileResDir)
##copy dp_ps, ss_ps file
if( dpSSFlag == True ):
mvCommand = "mv " + sourceDic + "*_dp.ps " + dpSSFileDic
runCommand(mvCommand)
mvCommand = "mv " + sourceDic + "*_ss.ps " + dpSSFileDic
runCommand(mvCommand)
else:
rmCommand = "rm " + sourceDic + "*_dp.ps " + dpSSFileDic
runCommand(rmCommand)
rmCommand = "rm " + sourceDic + "*_ss.ps " + dpSSFileDic
runCommand(rmCommand)
#end else
#structure are provided
if( lenList[0] == 2 ):
newFileDir = fileDir + "_ref"
fpw = open( newFileDir, "w" )
for curLine in lines:
elements = curLine.split("\t")
curPreMiRNAID = elements[0]
if( curPreMiRNAID not in structDic.keys() ):
continue
curPreMiRNAStruct = structDic[curPreMiRNAID]
fpw.write( curLine.strip() + "\t" + curPreMiRNAStruct + "\n" )
#end for
fpw.close()
#end if
#end else
return newFileDir
#end def
##merge list
def mergeList( listID, sep ):
if( sep == "" ):
res = ''.join(listID)
if( sep == "," ):
res = ','.join(listID)
if( sep == ";" ):
res = ';'.join(listID)
if( sep == ":" ):
res = ':'.join(listID)
return res
#end def
##run command line
def runCommand ( order ):
res = os.system( order )
if( res != 0 ):
print "Error to run order:", order
sys.exit()
#end if
#end fun
def uniqArrayLen( list2d ):
lenList = []
for i in range(len(list2d)):
lenList.append( len(list2d[i] ) )
#end for
lenSet = set(lenList)
return list(lenSet)
#end def
##transform list&list to 2-D array
def transform_list_2_array( list2d ):
Array2d = np.array( list2d )
return Array2d
#end def
##save prediction model from sklearn
def savePredModel( predModel, fileDir ):
_ = joblib.dump(predModel, fileDir, compress=9)
#end fun
##load prediction model
def loadPredModel( predModelFileDir ):
predModel = joblib.load(predModelFileDir)
return predModel
#end fun
##get miRNA length
def getMiRNALen (miRNASeq):
return len(miRNASeq)
#end def
##get miRNA GC content
def getGCContent (miRNASeq):
Len = getMiRNALen(miRNASeq)
gc = miRNASeq.count('G')
gc = gc + miRNASeq.count('g')
gc = gc + miRNASeq.count('C')
gc = gc + miRNASeq.count('c')
GCContent = 1.0*gc/Len
return GCContent
#end def
##get miRNA position on RNASequence, 0-based
def getMiRNAPosition (miRNASeq, RNASequence ):
startPos = RNASequence.find(miRNASeq)
endPos = startPos + getMiRNALen(miRNASeq)
return [startPos, endPos]
#end fun
##get miRNA structure
def getMiRNAStructure (miRNASeq, RNASequence, RNAStructure ):
[startPos, endPos] = getMiRNAPosition( miRNASeq, RNASequence )
mirnaStruct = RNAStructure[ startPos:endPos ]
return mirnaStruct
#end fun
####check whether there is a loop in mature miRNA
def getMirnaIncludedInLoop( RNASequence, RNAStructure, miRNASeq ):
flag = False
mirnaStruct = getMiRNAStructure( miRNASeq, RNASequence, RNAStructure )
if( ('(' in mirnaStruct) and (')' in mirnaStruct) ):
flag = True
return flag
#end fun
def matchRNAStructure( RNAStructure ):
RNALen = len(RNAStructure)
#first define a list with the same length of RNAStructure, at each position
#the value of matched position for current position
matchedPosList = [-1]*RNALen
stack = []
stackPos = []
for i in range(RNALen):
a = RNAStructure[i]
if( isParenthese(a) == False ):
continue
if( len(stack) == 0 ):
#empty stack, record item
stack.append(a)
stackPos.append(i)
else:
#pop last item in stack and stackPos
stack_lastItem = stack.pop()
stackPos_lastItem = stackPos.pop()
if( stack_lastItem == '(' and a == ')' ):
#meet a match, record matched position
matchedPosList[i] = stackPos_lastItem
matchedPosList[stackPos_lastItem] = i
continue
else:
#have to record
stack.append( stack_lastItem )
stackPos.append( stackPos_lastItem )
stack.append(a)
stackPos.append(i)
#end else
#end else
#end for i
return matchedPosList
#end fun
##get arm5 and arm3 location, 0-based coordination
def getTerminalLoopRegion( matchedPosList ):
#print matchedPosList
idx = -1
matchedRegionList = []
for ii in range(len(matchedPosList)):
curMatchedPos = matchedPosList[ii]
if( curMatchedPos == -1 ):
continue
curDistance = curMatchedPos - ii
matchedRegionList.append( [ii, curMatchedPos, curDistance] )
#end for ii
#find loop region
loopRegion = [-1,-1]
for ii in range(1, len(matchedRegionList) ):
[prePos1, prePos2, preDist] = matchedRegionList[ii-1]
[curPos1, curPos2, curDist] = matchedRegionList[ii]
if( prePos1 == curPos2 and curPos1 == prePos2 ):
loopRegion = [prePos1 + 1, prePos2 - 1]
break
#end if
#end for
if( loopRegion[0] == -1 or loopRegion[1] == -1 ):
print matchedPosList
print "Error to find loop region"
sys.exit()
else:
return loopRegion
#end def
def getMatchedPositions( startPos, endPos, matchedStructList ):
RNALen = len(matchedStructList)
#check pos
# if( startPos < 0 or endPos < 0 or startPos > RNALen or endPos > RNALen ):
# print "Warnning: matrched pos not correctly determined:", startPos, endPos, RNALen
# return [-1,-1]
#end if
if( startPos < 0 ):
startPos = 0
if( endPos < 0 ):
endPos = endPos
if( startPos > RNALen ):
startPos = RNALen - 1
if( endPos > RNALen ):
endPos = RNALen - 1
if( startPos == 0 and endPos == 0 ):
return [0,0]
matchedPosList = []
for i in range(startPos, endPos):
curPos = matchedStructList[i]
matchedPosList.append( curPos )
#end for i
if( matchedPosList[0] == -1 ):
idx = 0
for i in range(len(matchedPosList)):
if( matchedPosList[i] != -1 ):
idx = i
break
#end for i
matchedPos = matchedPosList[idx]
idxList = range(idx)
for i in idxList[::-1]:
matchedPos = matchedPos + 1
matchedPosList[i] = matchedPos
#end for i
#end if
if( matchedPosList[-1] == -1 ):
idxList = range(len(matchedPosList))
idx = 0
for i in idxList[::-1]:
if( matchedPosList[i] != -1 ):
idx = i
break
#end for i
matchedPos = matchedPosList[idx]
idx = idx + 1
for i in range(idx, len(matchedPosList)):
matchedPos = matchedPos - 1
matchedPosList[i] = matchedPos
#end if
if( matchedPosList[0] < 0 ):
matchedPosList[0] = 0
if( matchedPosList[0] > RNALen ):
matchedPosList[0] = RNALen - 1
if( matchedPosList[-1] < 0 ):
matchedPosList[-1] = 0
if( matchedPosList[-1] > RNALen ):
matchedPosList[-1] = RNALen - 1
return [matchedPosList[0], matchedPosList[-1]]
#end fun
###check miRNA located in which arm
def checkArm( RNASequence, RNAStructure, miRNASeq ):
# matchedRNAStructureList = matchRNAStructure(RNAStructure)
# [loopStart, loopEnd] = getTerminalLoopRegion( matchedRNAStructureList )
# [mirnaStart, mirnaEnd] = getMiRNAPosition(miRNASeq, RNASequence)
# arm = "loop"
# if( mirnaEnd < loopStart ):
# arm = "arm5"
# if( mirnaStart > loopEnd ):
# arm = "arm3"
armDetailedType = ""
if( getMirnaIncludedInLoop( RNASequence, RNAStructure, miRNASeq ) ):
armDetailedType = "loop"
#check arms
mirnaStruct = getMiRNAStructure( miRNASeq, RNASequence, RNAStructure )
armDetailedType = "unmatchedRegion"
if( '(' in mirnaStruct ):
armDetailedType = "arm5"
if( ')' in mirnaStruct ):
armDetailedType = "arm3"
return armDetailedType
#end fun
##remove mature miRNA in loops
def removeMiRNAInLoop( allSeq ):
res = []
for i in range(len(allSeq)):
[curMiRNAID, curPreMiRNAID, curMiRNASeq, curPreMiRNASeq, curPreMiRNAStructure] = allSeq[i]
curArmType = checkArm( curPreMiRNASeq, curPreMiRNAStructure, curMiRNASeq )
if( curArmType != "arm3" and curArmType != "arm5" ):
continue
res.append( allSeq[i] )
#end for i
return res
#end fun
##remove multiple miRNAs on one pre-miRNA arm
def removeMultipleMiRNAsOneArm ( allSeq ):
armStat_Dic = {}
for i in range(len(allSeq)):
[curMiRNAID, curPreMiRNAID, curMiRNASeq, curPreMiRNASeq, curPreMiRNAStructure] = allSeq[i]
curArmType = checkArm( curPreMiRNASeq, curPreMiRNAStructure, curMiRNASeq )
if( curArmType != "arm3" and curArmType != "arm5" ):
continue
if( curPreMiRNAID not in armStat_Dic ):
armStat_Dic[curPreMiRNAID] = [0,0]
tmp = armStat_Dic[curPreMiRNAID]
if( curArmType == "arm5" ):
tmp[0] = tmp[0] + 1
else:
tmp[1] = tmp[1] + 1
armStat_Dic[curPreMiRNAID] = tmp
#end for i
#print armStat_Dic
removedPreMiRNAs = []
res = []
for i in range(len(allSeq)):
[curMiRNAID, curPreMiRNAID, curMiRNASeq, curPreMiRNASeq, curPreMiRNAStructure] = allSeq[i]
#no miRNA on 5' and 3' arms
if( curPreMiRNAID not in armStat_Dic ):
removedPreMiRNAs.append(curPreMiRNAID)
continue
#no multiple miRNAs on one arm
armStatList = armStat_Dic[curPreMiRNAID]
if( (armStatList[0] > 1) or (armStatList[1] > 1) ):
print curPreMiRNAID, "multiple mature miRNAs on one arm, will be removed."
removedPreMiRNAs.append(curPreMiRNAID)
continue
res.append( allSeq[i] )
#end for i
arm5 = 0
arm3 = 0
armBoth = 0
for curKey in armStat_Dic.keys():
if( curKey in removedPreMiRNAs ):
continue
armStatList = armStat_Dic[curKey]
if( (armStatList[0] > 1) or (armStatList[1] > 1) ):
continue
if( (armStatList[0] == 1) and (armStatList[1] == 0) ):
arm5 = arm5 + 1
if( (armStatList[0] == 0) and (armStatList[1] == 1) ):
arm3 = arm3 + 1
if( (armStatList[0] == 1) and (armStatList[1] == 1) ):
armBoth = armBoth + 1
#end for curKey
print "Arm5\t", arm5, "\tarm3\t", arm3, "\tarmBoth\t", armBoth
return res
#end fun
##remove duplicate pre-miRNA sequence (one pre-miRNA, two anntoated mature miRNAs on both arms)
def refinePreMiRNASeq( allSeq ):
allSeq_RefDic = {}
for i in range(len(allSeq)):
[curMiRNAID, curPreMiRNAID, curMiRNASeq, curPreMiRNASeq, curPreMiRNAStructure] = allSeq[i]
curArmType = checkArm( curPreMiRNASeq, curPreMiRNAStructure, curMiRNASeq )
if( curArmType != "arm3" and curArmType != "arm5" ):
continue
#if( curArmType != "arm3" ):
# continue
if( curPreMiRNAID not in allSeq_RefDic.keys() ):
allSeq_RefDic[curPreMiRNAID] = allSeq[i]
else:
#not consider miRNA on arm3, if there is a mature miRNA on arm5
if( curArmType != "arm3" ):
allSeq_RefDic[curPreMiRNAID] = allSeq[i]
#end else
#end for i
#transfer dictionary to list
resDic = []
for curKey in allSeq_RefDic.keys():
resDic.append( allSeq_RefDic[curKey] )
#end for
return resDic
#end fun
##arm transform for mature miRNA
def armTransform( allSeq ):
res = []
for i in range(len(allSeq)):
[curMiRNAID, curPreMiRNAID, curMiRNASeq, curPreMiRNASeq, curPreMiRNAStructure] = allSeq[i]
armType = checkArm( curPreMiRNASeq, curPreMiRNAStructure, curMiRNASeq )
if( armType == "arm3" ):
curMiRNAStar = getMiRNAStar(curPreMiRNASeq, curPreMiRNAStructure, curMiRNASeq, matchedStructList = [] )
res.append( [curMiRNAID, curPreMiRNAID, curMiRNAStar, curPreMiRNASeq, curPreMiRNAStructure] )
else:
res.append( allSeq[i] )
#end else
#end for i
return res
#end fun
##get min and max values
def getMinMaxInArray( Array ):
Min = 1000000000000
Max = 0
for i in range( len(Array) ):
curValue = float(Array[i])
if( curValue < Min ):
Min = curValue
if( curValue > Max ):
Max = curValue
#end for i
return [Min, Max]
#end fun
##normalize Array to 0~1
def normalizeArray( Array ):
[Min, Max] = getMinMaxInArray(Array)
deltValue = Max - Min
ArrayNew = [0]*len(Array)
for i in range( len(ArrayNew) ):
curValue = float( Array[i] )
ArrayNew[i] = 1.0*(curValue - Min)/deltValue
#end for i
return ArrayNew
#end fun
##get sample index for cross validation
def cross_validation_sample_index( sampleNum, cv = 10 ):
x = np.arange(sampleNum)
random.shuffle(x)
cvlist = np.array_split(x, cv)
return cvlist
#end fun
##get cv samples
def cross_validation_round_i ( cvSampleList, Round_i, allSeq, resultDic ):
trainFile = resultDic + "cv_" + str(Round_i) + "_trainSamples.txt"
testFile = resultDic + "cv_" + str(Round_i) + "_testSamples.txt"
fpw_train = open(trainFile, "w")
fpw_test = open( testFile, "w")
for i in range(len(cvSampleList) ):
curCVSampleList = cvSampleList[i]
if( i == Round_i ):
#samples for test
for j in curCVSampleList:
[curMiRNAID, curPreMiRNAID, curMiRNASeq, curPreMiRNASeq, curPreMiRNAStructure] = allSeq[j]
fpw_test.write( curMiRNAID + "\t" + curPreMiRNAID + "\t" + curMiRNASeq + "\t" + curPreMiRNASeq + "\t" + curPreMiRNAStructure + "\n")
#end for j
else:
for j in curCVSampleList:
[curMiRNAID, curPreMiRNAID, curMiRNASeq, curPreMiRNASeq, curPreMiRNAStructure] = allSeq[j]
fpw_train.write( curMiRNAID + "\t" + curPreMiRNAID + "\t" + curMiRNASeq + "\t" + curPreMiRNASeq + "\t" + curPreMiRNAStructure + "\n")
#end for j
#end if
#end for i
fpw_train.close()
fpw_test.close()
return [trainFile, testFile]
#end fun
##transform miRNAdup format to two fasta sequences
def transform_miRNAdup_fasta(fileDir, miRNASeqFileDir, preMiRNASeqFileDir, preMiRNAStructFileDir ):
allSeq = readSequenceAndStructure(fileDir)
fpw_miRNA = open( miRNASeqFileDir, "w")
fpw_preMiRNA = open( preMiRNASeqFileDir, "w")
fpw_preMiRNAStruct = open( preMiRNAStructFileDir, "w")
for i in range(len(allSeq)):
[curMiRNAID, curPreMiRNAID, curMiRNASeq, curPreMiRNASeq, curPreMiRNAStructure] = allSeq[i]
fpw_miRNA.write( ">" + curMiRNAID + "\n" + curMiRNASeq + "\n")
fpw_preMiRNA.write( ">" + curMiRNAID + "\n" + curPreMiRNASeq + "\n")
fpw_preMiRNAStruct.write( ">" + curMiRNAID + "\n" + curPreMiRNASeq + "\n" + curPreMiRNAStructure + " (-20.00)" + "\n" )
#end for i
fpw_miRNA.close()
fpw_preMiRNA.close()
fpw_preMiRNAStruct.close()
#end fun
##transform miRNAdup format to validation file format
def transform_miRNAdup_forValidation(fileDir, validationFileDir ):
allSeq = readSequenceAndStructure(fileDir)
fpw_miRNA = open( validationFileDir, "w")
for i in range(len(allSeq)):
[curMiRNAID, curPreMiRNAID, curMiRNASeq, curPreMiRNASeq, curPreMiRNAStructure] = allSeq[i]
fpw_miRNA.write( curMiRNAID + "\t" + curMiRNASeq + "\t" + curPreMiRNASeq + "\n" )
#end for i
fpw_miRNA.close()
#end fun
################################################################################################
##function: get pre-miRNA sequences from miRBase, 20131215######################################
################################################################################################
def readSequenceAndStructure( SeqStructFileDir):
allInfo = list()
for line in open(SeqStructFileDir):
line = line.strip()
[miRNAID, pre_MiRNAID, mut_miRNASeq, pre_miRNASeq, pre_miRNAStruct] = line.split("\t")
allInfo.append( [miRNAID, pre_MiRNAID, mut_miRNASeq, pre_miRNASeq, pre_miRNAStruct] )
#end for
return allInfo
#end fun
################################################################################################
##check RNASequence, whether gap or white space column##########################################
################################################################################################
def checkSequenceAndStructure( RNASequence, RNAStructure ):
Seq = RNASequence
Str = RNAStructure
# Remove gap positions from sequence (and structure)
i = 0
while i < len(Seq):
if Seq[i] in "- ":
# Gap or white space column
Seq = Seq[:i] + Seq[i + 1:]
Str = Str[:i] + Str[i + 1:]
else:
i += 1
#end while
if( len(RNASequence) != len(Seq) ):
sys.exit("Error: gap or white space in sequence.")
#end fun
def isParenthese(ch):
if( ch=='(' or ch==')' ):
return True
else:
return False
#end fun
###############################################################################################
########Complement a string of IUPAC DNA nucleotides (output A C T G only).####################
########The string input are one-letter upper or lower case IUPAC nucleotides to complement.####
########A complemented string, ie A->T, T->A, C->G, G->C, U->A. Case is preserved.###############
################################################################################################
def nucleotideComplement (ch):
str = 'ACGTUacgtu'
chDict = {'A': 'U', 'U':'A', 'C':'G', 'G':'C', 'a': 'u', 'u':'a', 'c':'g', 'g':'c' }
if( ch not in str ):
return ch
else:
return chDict[ch]
#end fun
def dnaComplement( s ):
cgene = list(s)
for i in range( len(cgene) ):
cgene[i] = nucleotideComplement( cgene[i] )
#end for
str = ''.join(cgene)
return str
#end fun
def dnaReverseComplement(s):
s_c = dnaComplement(s)
return s_c[::-1]
#end fun
################################################################################################
################################################################################################
##get complementarity region
def computeComplementaritySequence(RNASequence, RNAStructure, miRNASeq, matchedStructList = [] ):
if( len(matchedStructList) == 0 ):
matchedStructList = matchRNAStructure( RNAStructure )
[mirnaStart, mirnaEnd] = getMiRNAPosition(miRNASeq, RNASequence)
[matchedPosStart, matchedPosEnd] = getMatchedPositions( mirnaStart, mirnaEnd, matchedStructList )
#print mirnaStart, "..", mirnaEnd, "\tmatchedPos:", matchedPosStart, "..", matchedPosEnd, RNASequence[matchedPosEnd:matchedPosStart+1], "\n"
if( matchedPosStart == 0 and matchedPosEnd == 0 ):
return 'N'*len(miRNASeq)
################################################################################
if( matchedPosStart < matchedPosEnd ):
return RNASequence[matchedPosStart: (matchedPosEnd+1)]
else:
subStr = RNASequence[matchedPosEnd: (matchedPosStart+1)]
return subStr[::-1]
#end else
size = getMiRNALen(miRNASeq)
[mirnaStart, mirnaEnd] = getMiRNAPosition(miRNASeq, RNASequence)
armType = checkArm( RNASequence, RNAStructure, miRNASeq )
miRNAStar = ""
if(armType == "arm5"):
#check whether there loop before miRNA
startToMirna = RNAStructure[0:mirnaStart]
#print RNASequence[0:mirnaStart]
#get open parenthesis minus close parenthesis between precursor start and mirna
openPar = startToMirna.count( '(') - startToMirna.count( ')' )
#analysing from the end of precursor if presence of loop
openParEnd=0
i=len(RNAStructure)-1
while ( openPar != openParEnd ):
if( RNAStructure[i]== ')' ):
openParEnd = openParEnd + 1
if( RNAStructure[i]== '(' ):
openParEnd = openParEnd - 1
if(openPar != openParEnd):
i = i - 1
#end while
#get complement
star=""
posOnStar = i
i = mirnaStart
while( i >= mirnaStart and i < mirnaEnd ):
posOnStar = posOnStar - 1
a = RNAStructure[i]
b = RNAStructure[posOnStar]
#print i, RNASequence[i], a, posOnStar, RNASequence[posOnStar], b
#for bulge before miRNA start position
if( i == mirnaStart and isParenthese(a) == True and isParenthese(b) == False ):
continue
if( isParenthese(a) == True and isParenthese(b) == True or a==b ):
star = star + RNASequence[posOnStar]
elif( a =='.' and isParenthese(b) == True ):
posOnStar = posOnStar + 1
elif( b =='.' and isParenthese(a) == True ):
star = star + RNASequence[posOnStar]
i = i - 1
i = i + 1
#end for i
miRNAStar = star[::-1]
elif( armType == "arm3"):
#end for 3'
EndToMirna = RNAStructure[mirnaStart+size: len(RNAStructure)]
#print EndToMirna, miRNA, RNAStructure[mirnaStart:(mirnaStart+size)], RNASequence[mirnaStart+size: len(RNAStructure)]
#get open parenthesis minus close parenthesis between precursor end and mirna end
closePar= EndToMirna.count( ')') - EndToMirna.count( '(');
#print closePar
#analysing from the end of precursor if presence of loop
openPar = 0
i = 0
while( openPar != closePar ):
if( RNAStructure[i] == '(' ):
openPar = openPar + 1
if( RNAStructure[i] == ')' ):
openPar = openPar - 1
if( openPar != closePar ):
i = i + 1
#end while
#get complement
star=""
posOnStar = i
#print RNAStructure[posOnStar + 1: posOnStar+ 31]
idxVec = range( mirnaStart, mirnaEnd )
i = mirnaEnd - 1
while( i >= mirnaStart and i < mirnaEnd ):
posOnStar = posOnStar + 1
a = RNAStructure[i]
b = RNAStructure[posOnStar]
#print RNASequence[i], RNASequence[posOnStar], a, b
#for a bulge after the miRNA end position
if( isParenthese(a) and i == (mirnaEnd - 1) and isParenthese(b) == False ):
continue
if( isParenthese(a) and isParenthese(b) or a==b ):
star = star + RNASequence[posOnStar]
elif( a == '.' and isParenthese(b) ):
posOnStar = posOnStar - 1
elif( b =='.' and isParenthese(a) ):
star = star + RNASequence[posOnStar]
i = i + 1
#end if
i = i - 1
#end while
miRNAStar = star[::-1]
else:
miRNAStar = 'N'*len(miRNASeq)
#end if..else
return miRNAStar
#end fun
########################################################################
##get miRNAStar#########################################################
########################################################################
def getMiRNAStar(RNASequence, RNAStructure, miRNASeq, matchedStructList = [] ):
if( len(matchedStructList) == 0 ):
matchedStructList = matchRNAStructure( RNAStructure )
[miRNAPosStart, miRNAPosEnd] = getMiRNAPosition( miRNASeq, RNASequence )
[matchedPosStart, matchedPosEnd] = getMatchedPositions( miRNAPosStart, miRNAPosEnd, matchedStructList )
matchedPosStart = matchedPosStart + 2
matchedPosEnd = matchedPosEnd + 2
RNALen = len(RNASequence)
if( matchedPosStart < 0 ):