-
Notifications
You must be signed in to change notification settings - Fork 82
/
iprscan-local.py
executable file
·380 lines (337 loc) · 13 KB
/
iprscan-local.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import multiprocessing
import subprocess
import time
import shutil
import funannotate.library as lib
from xml.etree import ElementTree as et
class MyFormatter(argparse.ArgumentDefaultsHelpFormatter):
def __init__(self, prog):
super(MyFormatter, self).__init__(prog, max_help_position=50)
parser = argparse.ArgumentParser(prog='funannotate-iprscan.py',
description='''Script to run InterProscan locally or with Docker''',
epilog="""Written by Jon Palmer (2017) nextgenusfs@gmail.com""",
formatter_class=MyFormatter)
parser.add_argument('-i', '--input', required=True,
help='FASTA file or funannotate folder')
parser.add_argument('-n', '--num', type=int, default=1000,
help='Number of files in each chunk')
parser.add_argument('-c', '--cpus', default=12, type=int,
help='Total number of CPUs')
parser.add_argument('-m', '--method', required=True,
choices=['local', 'docker'], help='Method to use')
parser.add_argument('--cpus_per_chunk', default=4, type=int,
help='Number of CPUs per IPR instance')
parser.add_argument('--iprscan_path', default='interproscan.sh',
help='Local Path to interproscan.sh')
parser.add_argument('-o', '--out', help='Final output XML file')
parser.add_argument('--debug', action='store_true', help='Keep intermediate files')
args = parser.parse_args()
def combine_xml(files, output):
first = None
for filename in files:
data = et.parse(filename).getroot()
if first is None:
first = data
else:
first.extend(data.getchildren())
#generate new tree
tree = et.ElementTree()
tree._setroot(first)
et.register_namespace("", "http://www.ebi.ac.uk/interpro/resources/schemas/interproscan5")
tree.write(output, encoding='utf-8', xml_declaration=True)
def checkDocker():
try:
proc = subprocess.Popen(
['docker', 'images'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError as e:
if e.errno == os.errno.ENOENT:
print('Docker is not installed, exiting.')
sys.exit(1)
stdout, stderr = proc.communicate()
if 'Cannot connect' in stderr:
print('Docker is not running, please launch Docker app and re-run script.')
sys.exit(1)
# now check for interproscan images
check = False
for line in stdout.split('\n'):
if line.startswith('blaxterlab/interproscan'):
check = True
if not check:
print('Downloading InterProScan Docker images:')
subprocess.call(['docker', 'pull', 'blaxterlab/interproscan'])
print('Docker InterProScan container is ready.')
def download(url, name):
import urllib2
file_name = name
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print("Downloading: {0} Bytes: {1}".format(url, file_size))
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
p = float(file_size_dl) / file_size
status = r"{0} [{1:.2%}]".format(file_size_dl, p)
status = status + chr(8)*(len(status)+1)
sys.stdout.write(status)
f.close()
def countfasta(input):
count = 0
with open(input, 'r') as f:
for line in f:
if line.startswith(">"):
count += 1
return count
def scan_linepos(path):
"""return a list of seek offsets of the beginning of each line"""
linepos = []
offset = 0
with open(path) as inf:
# WARNING: CPython 2.7 file.tell() is not accurate on file.next()
for line in inf:
linepos.append(offset)
offset += len(line)
return linepos
def return_lines(path, linepos, nstart, nstop):
"""return nsamp lines from path where line offsets are in linepos"""
offsets = linepos[nstart:nstop]
lines = []
with open(path) as inf:
for offset in offsets:
inf.seek(offset)
lines.append(inf.readline())
return lines
def split_fasta(input, outputdir, chunks):
# function to return line positions of fasta files for chunking
fastapos = []
position = 0
numseqs = 0
basename = os.path.basename(input).split('.fa', -1)[0]
with open(input, 'r') as infile:
for line in infile:
if line.startswith('>'):
numseqs += 1
fastapos.append(position)
position += 1
splits = []
n = int(numseqs / chunks)
num = 0
for i in range(chunks):
if i == 0:
start = 0
num = n
lastpos = fastapos[n+1]
else:
start = lastpos
num = num + n
try:
lastpos = fastapos[num+1] # find the n+1 seq
except IndexError:
lastpos = fastapos[-1]
splits.append((start, lastpos))
# check if output folder exists, if not create it
if not os.path.isdir(outputdir):
os.makedirs(outputdir)
# get line positions from file
linepos = scan_linepos(input)
# loop through the positions and write output
for i, x in enumerate(splits):
num = i+1
with open(os.path.join(outputdir, basename+'_'+str(num)+'.fasta'), 'w') as output:
lines = return_lines(input, linepos, x[0], x[1])
output.write('%s' % ''.join(lines))
def downloadIPRproperties(name, cpus):
download('https://raw.githubusercontent.com/ebi-pf-team/interproscan/5.22-61.0/core/jms-implementation/support-mini-x86-32/interproscan.properties', 'ipr.tmp')
with open(name, 'w') as outfile:
with open('ipr.tmp', 'r') as infile:
for line in infile:
if line.startswith('number.of.embedded.workers='):
outfile.write('number.of.embedded.workers=1\n')
elif line.startswith('maxnumber.of.embedded.workers='):
outfile.write('maxnumber.of.embedded.workers=%i\n' % cpus)
else:
outfile.write(line)
os.remove('ipr.tmp')
def runDocker(input):
current = os.getcwd()
UID = str(os.getuid())
GROUP = str(os.getgid())
prop = os.path.join(current, tmpdir, 'interproscan.properties')
cmd = ['docker', 'run', '-u', UID+':'+GROUP, '--rm', '-v', os.path.join(current, tmpdir)+':/dir',
'-v', os.path.join(current, tmpdir)+':/in', '-v', prop +
':/interproscan-5.22-61.0/interproscan.properties',
'blaxterlab/interproscan:latest', 'interproscan.sh', '-i', '/in/'+input, '-d', '/dir',
'-dp', '-f', 'XML', '-goterms', '-dra']
logfile = os.path.join(tmpdir, input.split('.fasta')[0])
logfile = logfile + '.log'
with open(logfile, 'w') as log:
log.write('%s\n' % ' '.join(cmd))
subprocess.call(cmd, cwd=tmpdir, stdout=log, stderr=log)
def safe_run(*args, **kwargs):
"""Call run(), catch exceptions."""
try:
runDocker(*args, **kwargs)
except Exception as e:
print("error: %s run(*%r, **%r)" % (e, args, kwargs))
def runLocal(input):
cmd = [iprpath, '-i', input, '-d', '.', '-f', 'XML', '-goterms', '-pa']
logfile = os.path.join(tmpdir, input.split('.fasta')[0])
logfile = logfile + '.log'
with open(logfile, 'w') as log:
subprocess.call(cmd, cwd=tmpdir, stdout=log, stderr=log)
def safe_run2(*args, **kwargs):
"""Call run(), catch exceptions."""
try:
runLocal(*args, **kwargs)
except Exception as e:
print("error: %s run(*%r, **%r)" % (e, args, kwargs))
def runMultiProgress(function, inputList, cpus):
# setup pool
p = multiprocessing.Pool(cpus)
# setup results and split over cpus
tasks = len(inputList)
results = []
for i in inputList:
results.append(p.apply_async(function, [i]))
# refresh pbar every 5 seconds
while True:
incomplete_count = sum(1 for x in results if not x.ready())
if incomplete_count == 0:
break
sys.stdout.write("Progress: %.2f%% \r" %
(float(tasks - incomplete_count) / tasks * 100))
sys.stdout.flush()
time.sleep(1)
p.close()
p.join()
# make temp directory
tmpdir = 'iprscan_' + str(os.getpid())
os.makedirs(tmpdir)
# check input, if folder
input = None
finalOut = None
if os.path.isfile(args.input):
input = args.input
if not args.out:
print('Please specify an output file, -o,--out.')
sys.exit(1)
finalOut = args.out
elif os.path.isdir(args.input): # now run through funannotate folders
# funannotate results 1) in update folder or 2) in predict folder
if os.path.isdir(os.path.join(args.input, 'update_results')):
inputdir = os.path.join(args.input, 'update_results')
outputdir = args.input
elif os.path.isdir(os.path.join(args.input, 'predict_results')):
inputdir = os.path.join(args.input, 'predict_results')
outputdir = args.input
else:
# here user specified the predict_results folder, or it is a custom folder
inputdir = os.path.join(args.input)
if not args.out:
print('Please specify an output file, -o,--out.')
sys.exit(1)
# get files that you need
for file in os.listdir(inputdir):
if file.endswith('.proteins.fa'):
input = os.path.join(inputdir, file)
if not args.out:
# setup output if funannotate outputdir
if not os.path.isdir(os.path.join(outputdir, 'annotate_misc')):
os.makedirs(os.path.join(outputdir, 'annotate_misc'))
finalOut = os.path.join(outputdir, 'annotate_misc', 'iprscan.xml')
else:
finalOut = args.out
else:
print('%s input does not exist' % args.input)
sys.exit(1)
if not input:
print('Error: could not parse input. Should be base funannotate folder or protein fasta file.')
sys.exit(1)
if not finalOut:
print('Error: could not parse output, specify')
# figure out number of chunks
count = countfasta(input)
print('Running InterProScan5 on %i proteins' % count)
if args.num > count:
chunks = 1
else:
chunks = int(round(count / float(args.num)))
if chunks == 1: # means we rounded down to 1, but we actually want to split this into 2
chunks = 2
threads = int(round(args.cpus / float(args.cpus_per_chunk)))
if threads < 1:
threads = 1
# split protein fasta files into chunks
if chunks > 1:
split_fasta(input, tmpdir, chunks)
else:
tmpfile = os.path.basename(input).split('.fa')[0]
shutil.copyfile(input, os.path.join(tmpdir, tmpfile+'.fasta'))
# get list of inputs
file_list = []
for file in os.listdir(tmpdir):
if file.endswith('.fasta'):
file_list.append(file)
if args.method == 'docker':
checkDocker()
ipr_properties = os.path.join(tmpdir, 'interproscan.properties')
downloadIPRproperties(ipr_properties, args.cpus_per_chunk)
if chunks > 1:
runMultiProgress(safe_run, file_list, threads)
else:
runDocker(file_list[0])
elif args.method == 'local':
if not args.iprscan_path:
print('You must specify location of interproscan.sh to --iprscan_path, exiting.')
sys.exit(1)
else:
if args.iprscan_path.endswith('interproscan.sh'):
iprpath = lib.which_path(args.iprscan_path)
else:
iprpath = os.path.join(args.iprscan_path, 'interproscan.sh')
if not os.path.isfile(iprpath):
print('%s is not a valid path to interproscan.sh' % iprpath)
sys.exit(1)
print('Important: you need to manually configure your interproscan.properties file for embedded workers.')
print('Will try to launch %i interproscan processes, adjust -c,--cpus for your system' % args.cpus)
if chunks > 1:
runMultiProgress(safe_run2, file_list, args.cpus)
else:
runLocal(file_list[0])
final_list = []
logfiles = []
for file in os.listdir(tmpdir):
if file.endswith('.xml'):
final_list.append(os.path.join(tmpdir, file))
elif file.endswith('.log'):
logfiles.append(os.path.join(tmpdir, file))
# apparently IPRscan XML has changed the header format, so now combine with ElementTree so no mistakes
combine_xml(final_list, finalOut)
# sometimes docker fails because can't mount from this directory, i.e. if not in docker preferences, check logfile
doublecheck = True
with open(logfiles[0], 'r') as logcheck:
for line in logcheck:
if line.startswith('docker:'):
if 'Error' in line:
print(line)
doublecheck = False
if doublecheck:
# check output file, if present and not empty, then delete temporary directory
if not args.debug:
if os.path.isfile(finalOut):
shutil.rmtree(tmpdir)
print('InterProScan5 search has completed successfully!')
print('Results are here: %s' % finalOut)
else:
print('Docker IPRscan run has failed, see log file: %s' % logfiles[0])