searchForMotifSites.py
11.1 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
#!/usr/bin/python3
from sys import argv
import subprocess
import inspect
from multiprocessing import Pool, TimeoutError, cpu_count
from os import path, makedirs, getcwd, chdir, devnull
# Retrieve Jar3D Paths from file EditMe
jar3dexec = ""
HLmotifDir = ""
ILmotifDir = ""
bminDir = path.dirname(path.abspath(inspect.getfile(inspect.currentframe())))
exec(compile(open(bminDir+"/EditMe").read(), '', 'exec'))
class Loop:
def __init__(self, header, subsequence, looptype, position):
self.header = header
self.seq = subsequence
self.type = looptype
self.position = position
def get_header(self):
return self.header[1:]
def subsequence(self):
return self.seq
class InsertionSite:
def __init__(self, loop, csv_line):
# BEWARE : jar3d csv output is crap because of java's locale settings.
# On french OSes, it uses commas to delimit the fields AND as floating point delimiters !!
# Parse with caution, and check what the csv output files look like on your system...
info = csv_line.split(',')
self.loop = loop # the Loop object that has been searched with jar3d
# position of the loop's components, so the motif's ones, in the query sequence.
self.position = loop.position
# Motif model identifier of the RNA 3D Motif Atlas
self.atlas_id = info[2]
# alignment score of the subsequence to the motif model
self.score = int(float(info[4]))
# should the motif model be inverted to fit the sequence ?
self.rotation = int(info[-2])
def __lt__(self, other):
return self.score < other.score
def __gt__(self, other):
return self.score > other.score
def enumerate_loops(s):
def printLoops(s, loops):
print(s)
for l in loops:
i = 0
m = ''
for c in l:
while i < c[0]:
m += ' '
i += 1
while i < c[1]+1:
m += '-'
i += 1
while i < len(s):
m += ' '
i += 1
print(m, "\tfound in position", l)
def resort(unclosedLoops):
loops.insert(len(loops)-1-unclosedLoops, loops[-1])
loops.pop(-1)
opened = []
openingStart = []
closingStart = []
loops = []
loopsUnclosed = 0
consecutiveOpenings = []
if s[0] == '(':
consecutiveOpenings.append(1)
consecutiveClosings = 0
lastclosed = -1
previous = ''
for i in range(len(s)):
# If we arrive on an unpaired segment
if s[i] == '.':
if previous == '(':
openingStart.append(i-1)
if previous == ')':
closingStart.append(i-1)
# Opening basepair
if s[i] == '(':
if previous == '(':
consecutiveOpenings[-1] += 1
else:
consecutiveOpenings.append(1)
if previous == ')':
closingStart.append(i-1)
# We have something like (...(
if len(openingStart) and openingStart[-1] == opened[-1]:
# Create a new loop starting with this component.
loops.append([(openingStart[-1], i)])
openingStart.pop(-1)
loopsUnclosed += 1
# We have something like )...( or even )(
if len(closingStart) and closingStart[-1] == lastclosed:
# Append a component to existing multiloop
loops[-1].append((closingStart[-1], i))
closingStart.pop(-1)
opened.append(i)
# Closing basepair
if s[i] == ')':
if previous == ')':
consecutiveClosings += 1
else:
consecutiveClosings = 1
# This is not supposed to happen in real data, but whatever.
if previous == '(':
openingStart.append(i-1)
# We have something like (...) or ()
if len(openingStart) and openingStart[-1] == opened[-1]:
# Create a new loop, and save it as already closed (HL)
loops.append([(openingStart[-1], i)])
openingStart.pop(-1)
resort(loopsUnclosed)
# We have something like )...)
if len(closingStart) and closingStart[-1] == lastclosed:
# Append a component to existing multiloop and close it.
loops[-1].append((closingStart[-1], i))
closingStart.pop(-1)
loopsUnclosed -= 1
resort(loopsUnclosed)
if i+1 < len(s):
if s[i+1] != ')': # We are on something like: ).
# an openingStart has not been correctly detected, like in ...((((((...)))...)))
if consecutiveClosings < consecutiveOpenings[-1]:
# Create a new loop (uncompleted)
loops.append([(opened[-2], opened[-1])])
loopsUnclosed += 1
# We just completed an HL+stem, like ...(((...))).., we can forget its info
if consecutiveClosings == consecutiveOpenings[-1]:
consecutiveClosings = 0
consecutiveOpenings.pop(-1)
else: # There are still several basepairs to remember, forget only the processed ones, keep the others
consecutiveOpenings[-1] -= consecutiveClosings
consecutiveClosings = 0
else: # We are on something like: ))
# we are on an closingStart that cannot be correctly detected, like in ...(((...(((...))))))
if consecutiveClosings == consecutiveOpenings[-1]:
# Append a component to the uncomplete loop and close it.
loops[-1].append((i, i+1))
loopsUnclosed -= 1
resort(loopsUnclosed)
# Forget the info about the processed stem.
consecutiveClosings = 0
consecutiveOpenings.pop(-1)
opened.pop(-1)
lastclosed = i
previous = s[i]
# print(i,"=",s[i],"\t", "consec. Op=", consecutiveOpenings,"Cl=",consecutiveClosings)
if (verbose):
printLoops(s, loops)
return(loops)
def launchJar3d(loop):
# write motif to a file
newpath = getcwd()+'/'+loop.header[1:]
if not path.exists(newpath):
makedirs(newpath)
chdir(newpath)
filename = loop.header[1:]+".fasta"
fasta = open(filename, 'w')
fasta.write('>'+loop.get_header()+'\n'+loop.subsequence()+'\n')
fasta.close()
# Launch Jar3D on it
if loop.type == 'h':
cmd = ["java", "-jar", jar3dexec, filename, HLmotifDir+"/all.txt",
loop.header[1:]+".HLloop.csv", loop.header[1:]+".HLseq.csv"]
else:
cmd = ["java", "-jar", jar3dexec, filename, ILmotifDir+"/all.txt",
loop.header[1:]+".ILloop.csv", loop.header[1:]+".ILseq.csv"]
if (verbose):
print(' '.join(cmd))
nowhere = open(devnull, 'w')
subprocess.call(cmd, stdout=nowhere)
nowhere.close()
# Retrieve results
insertion_sites = []
if loop.type == 'h':
capstype = "HL"
else:
capstype = "IL"
csv = open(loop.header[1:]+".%sseq.csv" % capstype, 'r')
l = csv.readline()
while l:
if "true" in l:
insertion_sites.append(InsertionSite(loop, l))
l = csv.readline()
csv.close()
# Cleaning
chdir("..")
subprocess.call(["rm", "-r", loop.header[1:]])
return insertion_sites
filename = argv[1]
verbose = int(argv[3])
basename = filename[0:filename.index('.')]
# Retrieving possible 2D structrures from RNAsubopt
if (verbose):
print("Retrieving possible 2D structures from RNAsubopt...")
dbn = open(basename+"_temp.dbn", "w")
subprocess.call(["RNAsubopt", "-i", filename], stdout=dbn)
dbn.close()
dbn = open(basename+"_temp.dbn", "r")
dbn.readline()
s = dbn.readline().split(' ')[0]
structures = []
l = dbn.readline()
while l:
structures.append(l.split(' ')[0])
l = dbn.readline()
dbn.close()
subprocess.call(["rm", basename+"_temp.dbn"])
for ss in structures:
if (verbose):
print(ss)
if (verbose):
print()
# Extracting probable loops from these structures
if (verbose):
print("Extracting probable loops from these structures...")
HLs = []
ILs = []
for ss in structures:
loop_candidates = enumerate_loops(ss)
for loop_candidate in loop_candidates:
if len(loop_candidate) == 1 and loop_candidate not in HLs:
HLs.append(loop_candidate)
if len(loop_candidate) == 2 and loop_candidate not in ILs:
ILs.append(loop_candidate)
if (verbose):
print("TOTAL:")
print(len(HLs), "probable hairpin loops found")
print(len(ILs), "probable internal loops")
print()
# Retrieve subsequences corresponding to the possible loops
if (verbose):
print("Retrieving subsequences corresponding to the possible loops...")
loops = []
for i, l in enumerate(HLs):
loops.append(Loop(">HL%d" % (i+1), s[l[0][0]-1:l[0][1]], "h", l))
if (verbose):
print()
print(loops[-1].get_header(), "\t\t", l)
print(loops[-1].subsequence())
for i, l in enumerate(ILs):
loops.append(
Loop(">IL%d" % (i+1), s[l[0][0]-1:l[0][1]]+'*'+s[l[1][0]-1:l[1][1]], "i", l))
if (verbose):
print()
print(loops[-1].get_header(), "\t\t", l)
print(loops[-1].subsequence())
if (verbose):
print()
# Scanning loop subsequences against motif database
if (verbose):
print("Scanning loop subsequences against motif database (using %d threads)..." %
(cpu_count()-1))
pool = Pool(processes=cpu_count()-1)
insertion_sites = [x for y in pool.map(launchJar3d, loops) for x in y]
insertion_sites.sort(reverse=True)
if (verbose):
print(len(insertion_sites), "insertions found:")
# Writing results to file
c = 0
resultsfile = open(basename+".sites.csv", "w")
resultsfile.write("Motif,Rotation,Score,Start1,End1,Start2,End2\n")
for site in insertion_sites:
if site.score > 10:
c += 1
string = "FOUND with score %d:\t\t possible insertion of motif " % site.score + site.atlas_id
if site.rotation:
string += " (reversed)"
string += (" on " + site.loop.get_header() + " at positions")
if (verbose):
print(string, site.loop.subsequence(),
'*'.join([str(x) for x in site.position]))
resultsfile.write(site.atlas_id+',' +
str(bool(site.rotation))+",%d" % site.score+',')
positions = [','.join([str(y) for y in x]) for x in site.position]
if len(positions) == 1:
positions.append("-,-")
resultsfile.write(','.join(positions)+'\n')
if c < len(insertion_sites):
if (verbose):
print("... and %d more with score(s) below 10." %
(len(insertion_sites)-c))
resultsfile.close()
# Lauching biominserter to get 2D predictions
subprocess.call([bminDir+"/bin/biominserter",
filename, basename+".sites.csv", argv[2], str(verbose), "1"])