comparison tools/samtools_idxstats/samtools_idxstats.py @ 0:d4412c04d7b1 draft

Uploaded v0.0.1 (as tested previously on the Test Tool Shed)
author peterjc
date Wed, 20 Nov 2013 12:27:33 -0500
parents
children 8945bad80f4a
comparison
equal deleted inserted replaced
-1:000000000000 0:d4412c04d7b1
1 #!/usr/bin/env python
2 """Wrapper for "samtools idxstats" for use in Galaxy.
3
4 This script takes exactly three command line arguments:
5 * Input BAM filename
6 * Input BAI filename (via Galaxy metadata)
7 * Output tabular filename
8
9 This messes about with the filenames to make samtools happy, then
10 runs "samtools idxstats" and captures the output to the desired
11 tabular file.
12 """
13 import sys
14 import os
15 import subprocess
16 import tempfile
17
18 if "-v" in sys.argv or "--version" in sys.argv:
19 #Galaxy seems to invert the order of the two lines
20 print "(Galaxy wrapper v0.0.1)"
21 cmd = "samtools 2>&1 | grep -i ^Version"
22 sys.exit(os.system(cmd))
23
24 def stop_err(msg, error_level=1):
25 """Print error message to stdout and quit with given error level."""
26 sys.stderr.write("%s\n" % msg)
27 sys.exit(error_level)
28
29 if len(sys.argv) != 4:
30 stop_err("Require three arguments: BAM, BAI, tabular filenames")
31
32 bam_filename, bai_filename, tabular_filename = sys.argv[1:]
33
34 if not os.path.isfile(bam_filename):
35 stop_err("Input BAM file not found: %s" % bam_filename)
36 if not os.path.isfile(bai_filename):
37 if bai_filename == "None":
38 stop_err("Error: Galaxy did not index your BAM file")
39 stop_err("Input BAI file not found: %s" % bai_filename)
40
41 #Assign sensible names with real extensions, and setup symlinks:
42 tmp_dir = tempfile.mkdtemp()
43 bam_file = os.path.join(tmp_dir, "temp.bam")
44 bai_file = os.path.join(tmp_dir, "temp.bam.bai")
45 os.symlink(os.path.abspath(bam_filename), bam_file)
46 os.symlink(os.path.abspath(bai_filename), bai_file)
47 assert os.path.isfile(bam_file), bam_file
48 assert os.path.isfile(bai_file), bai_file
49 assert os.path.isfile(bam_file + ".bai"), bam_file
50
51 #Run samtools idxstats:
52 cmd = "samtools idxstats %s > %s" % (bam_file, tabular_filename)
53 return_code = os.system(cmd)
54
55 #Remove the temp symlinks:
56 os.remove(bam_file)
57 os.remove(bai_file)
58 os.rmdir(tmp_dir)
59
60 if return_code:
61 stop_err("Return code %i from command:\n%s" % (return_code, cmd))