0
|
1 """
|
|
2 bam_to_scidx.py
|
|
3
|
|
4 Input: BAM file
|
|
5 Output: Converted scidx file
|
|
6 """
|
|
7 import optparse
|
|
8 import os
|
|
9 import shutil
|
|
10 import subprocess
|
|
11 import sys
|
|
12 import tempfile
|
|
13
|
|
14 BUFF_SIZE = 1048576
|
|
15
|
|
16
|
|
17 def get_stderr_exception(tmp_err, tmp_stderr):
|
|
18 """
|
|
19 Return a stderr string of reasonable size.
|
|
20 """
|
|
21 tmp_stderr.close()
|
|
22 # Get stderr, allowing for case where it's very large.
|
|
23 tmp_stderr = open(tmp_err, 'rb')
|
|
24 stderr_str = ''
|
|
25 buffsize = BUFF_SIZE
|
|
26 try:
|
|
27 while True:
|
|
28 stderr_str += tmp_stderr.read(buffsize)
|
|
29 if not stderr_str or len(stderr_str) % buffsize != 0:
|
|
30 break
|
|
31 except OverflowError:
|
|
32 pass
|
|
33 tmp_stderr.close()
|
|
34 return stderr_str
|
|
35
|
|
36
|
|
37 def stop_err(msg):
|
|
38 sys.stderr.write(msg)
|
|
39 sys.exit(1)
|
|
40
|
|
41
|
|
42 parser = optparse.OptionParser()
|
|
43 parser.add_option('-j', '--jar_file', dest='jar_file', type='string', help='BAMtoIDX.jar')
|
|
44 parser.add_option('-b', '--input_bam', dest='input_bam', type='string', help='Input dataset in BAM format')
|
|
45 parser.add_option('-i', '--input_bai', dest='input_bai', type='string', help='Input dataset index')
|
|
46 parser.add_option('-r', '--read', dest='read', type='int', default=0, help='Reads.')
|
|
47 parser.add_option('-o', '--output', dest='output', type='string', help='Output dataset in scidx format')
|
|
48 options, args = parser.parse_args()
|
|
49
|
|
50 tmp_dir = tempfile.mkdtemp(prefix='tmp-scidx-')
|
|
51 tmp_out = tempfile.NamedTemporaryFile().name
|
|
52 tmp_stdout = open(tmp_out, 'wb')
|
|
53 tmp_err = tempfile.NamedTemporaryFile().name
|
|
54 tmp_stderr = open(tmp_err, 'wb')
|
|
55
|
|
56 # Link input BAM file and associated index file into the working directory.
|
|
57 input_data_file_name = "input.bam"
|
|
58 os.link(options.input_bam, os.path.join(tmp_dir, input_data_file_name))
|
|
59 os.link(options.input_bai, os.path.join(tmp_dir, "%s.bai" % input_data_file_name))
|
|
60
|
|
61 cmd = "java -jar %s -b %s -s %d -o %s" % (options.jar_file, input_data_file_name, options.read, options.output)
|
|
62 proc = subprocess.Popen(args=cmd, stdout=tmp_stdout, stderr=tmp_stderr, shell=True, cwd=tmp_dir)
|
|
63 return_code = proc.wait()
|
|
64 if return_code != 0:
|
|
65 error_message = get_stderr_exception(tmp_err, tmp_stderr)
|
|
66 stop_err(error_message)
|
|
67
|
|
68 if tmp_dir and os.path.exists(tmp_dir):
|
|
69 shutil.rmtree(tmp_dir)
|