annotate tools/samtools/sam_to_bam.py @ 2:c2a356708570

Uploaded
author xuebing
date Fri, 09 Mar 2012 19:45:42 -0500
parents 9071e359b9a3
children
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
0
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
1 #!/usr/bin/env python
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
2 """
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
3 Converts SAM data to sorted BAM data.
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
4 usage: sam_to_bam.py [options]
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
5 --input1: SAM file to be converted
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
6 --dbkey: dbkey value
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
7 --ref_file: Reference file if choosing from history
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
8 --output1: output dataset in bam format
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
9 --index_dir: GALAXY_DATA_INDEX_DIR
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
10 """
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
11
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
12 import optparse, os, sys, subprocess, tempfile, shutil, gzip
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
13 from galaxy import eggs
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
14 import pkg_resources; pkg_resources.require( "bx-python" )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
15 from bx.cookbook import doc_optparse
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
16 from galaxy import util
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
17
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
18 def stop_err( msg ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
19 sys.stderr.write( '%s\n' % msg )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
20 sys.exit()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
21
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
22 def check_seq_file( dbkey, cached_seqs_pointer_file ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
23 seq_path = ''
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
24 for line in open( cached_seqs_pointer_file ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
25 line = line.rstrip( '\r\n' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
26 if line and not line.startswith( '#' ) and line.startswith( 'index' ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
27 fields = line.split( '\t' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
28 if len( fields ) < 3:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
29 continue
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
30 if fields[1] == dbkey:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
31 seq_path = fields[2].strip()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
32 break
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
33 return seq_path
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
34
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
35 def __main__():
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
36 #Parse Command Line
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
37 parser = optparse.OptionParser()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
38 parser.add_option( '', '--input1', dest='input1', help='The input SAM dataset' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
39 parser.add_option( '', '--dbkey', dest='dbkey', help='The build of the reference dataset' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
40 parser.add_option( '', '--ref_file', dest='ref_file', help='The reference dataset from the history' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
41 parser.add_option( '', '--output1', dest='output1', help='The output BAM dataset' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
42 parser.add_option( '', '--index_dir', dest='index_dir', help='GALAXY_DATA_INDEX_DIR' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
43 ( options, args ) = parser.parse_args()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
44
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
45 # output version # of tool
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
46 try:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
47 tmp = tempfile.NamedTemporaryFile().name
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
48 tmp_stdout = open( tmp, 'wb' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
49 proc = subprocess.Popen( args='samtools 2>&1', shell=True, stdout=tmp_stdout )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
50 tmp_stdout.close()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
51 returncode = proc.wait()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
52 stdout = None
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
53 for line in open( tmp_stdout.name, 'rb' ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
54 if line.lower().find( 'version' ) >= 0:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
55 stdout = line.strip()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
56 break
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
57 if stdout:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
58 sys.stdout.write( 'Samtools %s\n' % stdout )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
59 else:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
60 raise Exception
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
61 except:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
62 sys.stdout.write( 'Could not determine Samtools version\n' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
63
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
64 cached_seqs_pointer_file = '%s/sam_fa_indices.loc' % options.index_dir
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
65 if not os.path.exists( cached_seqs_pointer_file ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
66 stop_err( 'The required file (%s) does not exist.' % cached_seqs_pointer_file )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
67 # If found for the dbkey, seq_path will look something like /galaxy/data/equCab2/sam_index/equCab2.fa,
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
68 # and the equCab2.fa file will contain fasta sequences.
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
69 seq_path = check_seq_file( options.dbkey, cached_seqs_pointer_file )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
70 tmp_dir = tempfile.mkdtemp()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
71 if not options.ref_file or options.ref_file == 'None':
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
72 # We're using locally cached reference sequences( e.g., /galaxy/data/equCab2/sam_index/equCab2.fa ).
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
73 # The indexes for /galaxy/data/equCab2/sam_index/equCab2.fa will be contained in
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
74 # a file named /galaxy/data/equCab2/sam_index/equCab2.fa.fai
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
75 fai_index_file_base = seq_path
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
76 fai_index_file_path = '%s.fai' % seq_path
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
77 if not os.path.exists( fai_index_file_path ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
78 #clean up temp files
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
79 if os.path.exists( tmp_dir ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
80 shutil.rmtree( tmp_dir )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
81 stop_err( 'No sequences are available for build (%s), request them by reporting this error.' % options.dbkey )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
82 else:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
83 try:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
84 # Create indexes for history reference ( e.g., ~/database/files/000/dataset_1.dat ) using samtools faidx, which will:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
85 # - index reference sequence in the FASTA format or extract subsequence from indexed reference sequence
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
86 # - if no region is specified, faidx will index the file and create <ref.fasta>.fai on the disk
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
87 # - if regions are specified, the subsequences will be retrieved and printed to stdout in the FASTA format
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
88 # - the input file can be compressed in the RAZF format.
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
89 # IMPORTANT NOTE: a real weakness here is that we are creating indexes for the history dataset
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
90 # every time we run this tool. It would be nice if we could somehow keep track of user's specific
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
91 # index files so they could be re-used.
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
92 fai_index_file_base = tempfile.NamedTemporaryFile( dir=tmp_dir ).name
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
93 # At this point, fai_index_file_path will look something like /tmp/dataset_13.dat
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
94 os.symlink( options.ref_file, fai_index_file_base )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
95 fai_index_file_path = '%s.fai' % fai_index_file_base
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
96 command = 'samtools faidx %s' % fai_index_file_base
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
97 tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
98 tmp_stderr = open( tmp, 'wb' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
99 proc = subprocess.Popen( args=command, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
100 returncode = proc.wait()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
101 tmp_stderr.close()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
102 # get stderr, allowing for case where it's very large
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
103 tmp_stderr = open( tmp, 'rb' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
104 stderr = ''
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
105 buffsize = 1048576
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
106 try:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
107 while True:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
108 stderr += tmp_stderr.read( buffsize )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
109 if not stderr or len( stderr ) % buffsize != 0:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
110 break
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
111 except OverflowError:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
112 pass
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
113 tmp_stderr.close()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
114 if returncode != 0:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
115 raise Exception, stderr
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
116 if os.path.getsize( fai_index_file_path ) == 0:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
117 raise Exception, 'Index file empty, there may be an error with your reference file or settings.'
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
118 except Exception, e:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
119 #clean up temp files
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
120 if os.path.exists( tmp_dir ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
121 shutil.rmtree( tmp_dir )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
122 stop_err( 'Error creating indexes from reference (%s), %s' % ( options.ref_file, str( e ) ) )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
123 try:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
124 # Extract all alignments from the input SAM file to BAM format ( since no region is specified, all the alignments will be extracted ).
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
125 tmp_aligns_file = tempfile.NamedTemporaryFile( dir=tmp_dir )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
126 tmp_aligns_file_name = tmp_aligns_file.name
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
127 tmp_aligns_file.close()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
128 command = 'samtools view -bt %s -o %s %s' % ( fai_index_file_path, tmp_aligns_file_name, options.input1 )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
129 tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
130 tmp_stderr = open( tmp, 'wb' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
131 proc = subprocess.Popen( args=command, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
132 returncode = proc.wait()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
133 tmp_stderr.close()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
134 # get stderr, allowing for case where it's very large
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
135 tmp_stderr = open( tmp, 'rb' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
136 stderr = ''
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
137 buffsize = 1048576
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
138 try:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
139 while True:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
140 stderr += tmp_stderr.read( buffsize )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
141 if not stderr or len( stderr ) % buffsize != 0:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
142 break
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
143 except OverflowError:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
144 pass
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
145 tmp_stderr.close()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
146 if returncode != 0:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
147 raise Exception, stderr
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
148 except Exception, e:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
149 #clean up temp files
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
150 if os.path.exists( tmp_dir ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
151 shutil.rmtree( tmp_dir )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
152 stop_err( 'Error extracting alignments from (%s), %s' % ( options.input1, str( e ) ) )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
153 try:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
154 # Sort alignments by leftmost coordinates. File <out.prefix>.bam will be created. This command
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
155 # may also create temporary files <out.prefix>.%d.bam when the whole alignment cannot be fitted
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
156 # into memory ( controlled by option -m ).
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
157 tmp_sorted_aligns_file = tempfile.NamedTemporaryFile( dir=tmp_dir )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
158 tmp_sorted_aligns_file_name = tmp_sorted_aligns_file.name
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
159 tmp_sorted_aligns_file.close()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
160 command = 'samtools sort %s %s' % ( tmp_aligns_file_name, tmp_sorted_aligns_file_name )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
161 tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
162 tmp_stderr = open( tmp, 'wb' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
163 proc = subprocess.Popen( args=command, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
164 returncode = proc.wait()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
165 tmp_stderr.close()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
166 # get stderr, allowing for case where it's very large
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
167 tmp_stderr = open( tmp, 'rb' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
168 stderr = ''
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
169 buffsize = 1048576
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
170 try:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
171 while True:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
172 stderr += tmp_stderr.read( buffsize )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
173 if not stderr or len( stderr ) % buffsize != 0:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
174 break
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
175 except OverflowError:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
176 pass
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
177 tmp_stderr.close()
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
178 if returncode != 0:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
179 raise Exception, stderr
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
180 except Exception, e:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
181 #clean up temp files
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
182 if os.path.exists( tmp_dir ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
183 shutil.rmtree( tmp_dir )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
184 stop_err( 'Error sorting alignments from (%s), %s' % ( tmp_aligns_file_name, str( e ) ) )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
185 # Move tmp_aligns_file_name to our output dataset location
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
186 sorted_bam_file = '%s.bam' % tmp_sorted_aligns_file_name
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
187 shutil.move( sorted_bam_file, options.output1 )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
188 #clean up temp files
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
189 if os.path.exists( tmp_dir ):
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
190 shutil.rmtree( tmp_dir )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
191 # check that there are results in the output file
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
192 if os.path.getsize( options.output1 ) > 0:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
193 sys.stdout.write( 'SAM file converted to BAM' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
194 else:
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
195 stop_err( 'Error creating sorted version of BAM file.' )
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
196
9071e359b9a3 Uploaded
xuebing
parents:
diff changeset
197 if __name__=="__main__": __main__()