0
|
1 #!/usr/bin/env python
|
|
2
|
|
3 """
|
|
4 Runs BWA on single-end or paired-end data.
|
|
5 Produces a SAM file containing the mappings.
|
|
6 Works with BWA version 0.5.9.
|
|
7
|
|
8 usage: bwa_wrapper.py [options]
|
|
9
|
|
10 See below for options
|
|
11 """
|
|
12
|
|
13 import optparse, os, shutil, subprocess, sys, tempfile
|
|
14
|
|
15 def stop_err( msg ):
|
|
16 sys.stderr.write( '%s\n' % msg )
|
|
17 sys.exit()
|
|
18
|
|
19 def check_is_double_encoded( fastq ):
|
|
20 # check that first read is bases, not one base followed by numbers
|
|
21 bases = [ 'A', 'C', 'G', 'T', 'a', 'c', 'g', 't', 'N' ]
|
|
22 nums = [ '0', '1', '2', '3' ]
|
|
23 for line in file( fastq, 'rb'):
|
|
24 if not line.strip() or line.startswith( '@' ):
|
|
25 continue
|
|
26 if len( [ b for b in line.strip() if b in nums ] ) > 0:
|
|
27 return False
|
|
28 elif line.strip()[0] in bases and len( [ b for b in line.strip() if b in bases ] ) == len( line.strip() ):
|
|
29 return True
|
|
30 else:
|
|
31 raise Exception, 'First line in first read does not appear to be a valid FASTQ read in either base-space or color-space'
|
|
32 raise Exception, 'There is no non-comment and non-blank line in your FASTQ file'
|
|
33
|
|
34 def __main__():
|
|
35 #Parse Command Line
|
|
36 parser = optparse.OptionParser()
|
|
37 parser.add_option( '-t', '--threads', dest='threads', help='The number of threads to use' )
|
|
38 parser.add_option( '-c', '--color-space', dest='color_space', action='store_true', help='If the input files are SOLiD format' )
|
|
39 parser.add_option( '-r', '--ref', dest='ref', help='The reference genome to use or index' )
|
|
40 parser.add_option( '-f', '--input1', dest='fastq', help='The (forward) fastq file to use for the mapping' )
|
|
41 parser.add_option( '-F', '--input2', dest='rfastq', help='The reverse fastq file to use for mapping if paired-end data' )
|
|
42 parser.add_option( '-u', '--output', dest='output', help='The file to save the output (SAM format)' )
|
|
43 parser.add_option( '-g', '--genAlignType', dest='genAlignType', help='The type of pairing (single or paired)' )
|
|
44 parser.add_option( '-p', '--params', dest='params', help='Parameter setting to use (pre_set or full)' )
|
|
45 parser.add_option( '-s', '--fileSource', dest='fileSource', help='Whether to use a previously indexed reference sequence or one form history (indexed or history)' )
|
|
46 parser.add_option( '-n', '--maxEditDist', dest='maxEditDist', help='Maximum edit distance if integer' )
|
|
47 parser.add_option( '-m', '--fracMissingAligns', dest='fracMissingAligns', help='Fraction of missing alignments given 2% uniform base error rate if fraction' )
|
|
48 parser.add_option( '-o', '--maxGapOpens', dest='maxGapOpens', help='Maximum number of gap opens' )
|
|
49 parser.add_option( '-e', '--maxGapExtens', dest='maxGapExtens', help='Maximum number of gap extensions' )
|
|
50 parser.add_option( '-d', '--disallowLongDel', dest='disallowLongDel', help='Disallow a long deletion within specified bps' )
|
|
51 parser.add_option( '-i', '--disallowIndel', dest='disallowIndel', help='Disallow indel within specified bps' )
|
|
52 parser.add_option( '-l', '--seed', dest='seed', help='Take the first specified subsequences' )
|
|
53 parser.add_option( '-k', '--maxEditDistSeed', dest='maxEditDistSeed', help='Maximum edit distance to the seed' )
|
|
54 parser.add_option( '-M', '--mismatchPenalty', dest='mismatchPenalty', help='Mismatch penalty' )
|
|
55 parser.add_option( '-O', '--gapOpenPenalty', dest='gapOpenPenalty', help='Gap open penalty' )
|
|
56 parser.add_option( '-E', '--gapExtensPenalty', dest='gapExtensPenalty', help='Gap extension penalty' )
|
|
57 parser.add_option( '-R', '--suboptAlign', dest='suboptAlign', default=None, help='Proceed with suboptimal alignments even if the top hit is a repeat' )
|
|
58 parser.add_option( '-N', '--noIterSearch', dest='noIterSearch', help='Disable iterative search' )
|
|
59 parser.add_option( '-T', '--outputTopN', dest='outputTopN', help='Maximum number of alignments to output in the XA tag for reads paired properly' )
|
|
60 parser.add_option( '', '--outputTopNDisc', dest='outputTopNDisc', help='Maximum number of alignments to output in the XA tag for disconcordant read pairs (excluding singletons)' )
|
|
61 parser.add_option( '-S', '--maxInsertSize', dest='maxInsertSize', help='Maximum insert size for a read pair to be considered mapped good' )
|
|
62 parser.add_option( '-P', '--maxOccurPairing', dest='maxOccurPairing', help='Maximum occurrences of a read for pairings' )
|
|
63 parser.add_option( '', '--rgid', dest='rgid', help='Read group identifier' )
|
|
64 parser.add_option( '', '--rgcn', dest='rgcn', help='Sequencing center that produced the read' )
|
|
65 parser.add_option( '', '--rgds', dest='rgds', help='Description' )
|
|
66 parser.add_option( '', '--rgdt', dest='rgdt', help='Date that run was produced (ISO8601 format date or date/time, like YYYY-MM-DD)' )
|
|
67 parser.add_option( '', '--rgfo', dest='rgfo', help='Flow order' )
|
|
68 parser.add_option( '', '--rgks', dest='rgks', help='The array of nucleotide bases that correspond to the key sequence of each read' )
|
|
69 parser.add_option( '', '--rglb', dest='rglb', help='Library name' )
|
|
70 parser.add_option( '', '--rgpg', dest='rgpg', help='Programs used for processing the read group' )
|
|
71 parser.add_option( '', '--rgpi', dest='rgpi', help='Predicted median insert size' )
|
|
72 parser.add_option( '', '--rgpl', dest='rgpl', choices=[ 'CAPILLARY', 'LS454', 'ILLUMINA', 'SOLID', 'HELICOS', 'IONTORRENT' and 'PACBIO' ], help='Platform/technology used to produce the reads' )
|
|
73 parser.add_option( '', '--rgpu', dest='rgpu', help='Platform unit (e.g. flowcell-barcode.lane for Illumina or slide for SOLiD)' )
|
|
74 parser.add_option( '', '--rgsm', dest='rgsm', help='Sample' )
|
|
75 parser.add_option( '-D', '--dbkey', dest='dbkey', help='Dbkey for reference genome' )
|
|
76 parser.add_option( '-X', '--do_not_build_index', dest='do_not_build_index', action='store_true', help="Don't build index" )
|
|
77 parser.add_option( '-H', '--suppressHeader', dest='suppressHeader', help='Suppress header' )
|
|
78 parser.add_option( '-I', '--illumina1.3', dest='illumina13qual', help='Input FASTQ files have Illuina 1.3 quality scores' )
|
2
|
79 parser.add_option( '', '--meta_tsv', dest='metadata_tsv', help='Meta data for filling things like sequencing center' )
|
0
|
80 (options, args) = parser.parse_args()
|
|
81
|
|
82 # output version # of tool
|
|
83 try:
|
|
84 tmp = tempfile.NamedTemporaryFile().name
|
|
85 tmp_stdout = open( tmp, 'wb' )
|
|
86 proc = subprocess.Popen( args='bwa 2>&1', shell=True, stdout=tmp_stdout )
|
|
87 tmp_stdout.close()
|
|
88 returncode = proc.wait()
|
|
89 stdout = None
|
|
90 for line in open( tmp_stdout.name, 'rb' ):
|
|
91 if line.lower().find( 'version' ) >= 0:
|
|
92 stdout = line.strip()
|
|
93 break
|
|
94 if stdout:
|
|
95 sys.stdout.write( 'BWA %s\n' % stdout )
|
|
96 else:
|
|
97 raise Exception
|
|
98 except:
|
|
99 sys.stdout.write( 'Could not determine BWA version\n' )
|
|
100
|
|
101 # check for color space fastq that's not double-encoded and exit if appropriate
|
|
102 if options.color_space:
|
|
103 if not check_is_double_encoded( options.fastq ):
|
|
104 stop_err( 'Your file must be double-encoded (it must be converted from "numbers" to "bases"). See the help section for details' )
|
|
105 if options.genAlignType == 'paired':
|
|
106 if not check_is_double_encoded( options.rfastq ):
|
|
107 stop_err( 'Your reverse reads file must also be double-encoded (it must be converted from "numbers" to "bases"). See the help section for details' )
|
|
108
|
|
109 fastq = options.fastq
|
|
110 if options.rfastq:
|
|
111 rfastq = options.rfastq
|
|
112
|
|
113 # set color space variable
|
|
114 if options.color_space:
|
|
115 color_space = '-c'
|
|
116 else:
|
|
117 color_space = ''
|
|
118
|
|
119 # make temp directory for placement of indices
|
|
120 tmp_index_dir = tempfile.mkdtemp()
|
|
121 tmp_dir = tempfile.mkdtemp()
|
|
122 # index if necessary
|
|
123 if options.fileSource == 'history' and not options.do_not_build_index:
|
|
124 ref_file = tempfile.NamedTemporaryFile( dir=tmp_index_dir )
|
|
125 ref_file_name = ref_file.name
|
|
126 ref_file.close()
|
|
127 os.symlink( options.ref, ref_file_name )
|
|
128 # determine which indexing algorithm to use, based on size
|
|
129 try:
|
|
130 size = os.stat( options.ref ).st_size
|
|
131 if size <= 2**30:
|
|
132 indexingAlg = 'is'
|
|
133 else:
|
|
134 indexingAlg = 'bwtsw'
|
|
135 except:
|
|
136 indexingAlg = 'is'
|
|
137 indexing_cmds = '%s -a %s' % ( color_space, indexingAlg )
|
|
138 cmd1 = 'bwa index %s %s' % ( indexing_cmds, ref_file_name )
|
|
139 try:
|
|
140 tmp = tempfile.NamedTemporaryFile( dir=tmp_index_dir ).name
|
|
141 tmp_stderr = open( tmp, 'wb' )
|
|
142 proc = subprocess.Popen( args=cmd1, shell=True, cwd=tmp_index_dir, stderr=tmp_stderr.fileno() )
|
|
143 returncode = proc.wait()
|
|
144 tmp_stderr.close()
|
|
145 # get stderr, allowing for case where it's very large
|
|
146 tmp_stderr = open( tmp, 'rb' )
|
|
147 stderr = ''
|
|
148 buffsize = 1048576
|
|
149 try:
|
|
150 while True:
|
|
151 stderr += tmp_stderr.read( buffsize )
|
|
152 if not stderr or len( stderr ) % buffsize != 0:
|
|
153 break
|
|
154 except OverflowError:
|
|
155 pass
|
|
156 tmp_stderr.close()
|
|
157 if returncode != 0:
|
|
158 raise Exception, stderr
|
|
159 except Exception, e:
|
|
160 # clean up temp dirs
|
|
161 if os.path.exists( tmp_index_dir ):
|
|
162 shutil.rmtree( tmp_index_dir )
|
|
163 if os.path.exists( tmp_dir ):
|
|
164 shutil.rmtree( tmp_dir )
|
|
165 stop_err( 'Error indexing reference sequence. ' + str( e ) )
|
|
166 else:
|
|
167 ref_file_name = options.ref
|
|
168 if options.illumina13qual:
|
|
169 illumina_quals = "-I"
|
|
170 else:
|
|
171 illumina_quals = ""
|
|
172
|
|
173 # set up aligning and generate aligning command options
|
|
174 if options.params == 'pre_set':
|
|
175 aligning_cmds = '-t %s %s %s' % ( options.threads, color_space, illumina_quals )
|
|
176 gen_alignment_cmds = ''
|
|
177 else:
|
|
178 if options.maxEditDist != '0':
|
|
179 editDist = options.maxEditDist
|
|
180 else:
|
|
181 editDist = options.fracMissingAligns
|
|
182 if options.seed != '-1':
|
|
183 seed = '-l %s' % options.seed
|
|
184 else:
|
|
185 seed = ''
|
|
186 if options.suboptAlign:
|
|
187 suboptAlign = '-R "%s"' % ( options.suboptAlign )
|
|
188 else:
|
|
189 suboptAlign = ''
|
|
190 if options.noIterSearch == 'true':
|
|
191 noIterSearch = '-N'
|
|
192 else:
|
|
193 noIterSearch = ''
|
|
194 aligning_cmds = '-n %s -o %s -e %s -d %s -i %s %s -k %s -t %s -M %s -O %s -E %s %s %s %s %s' % \
|
|
195 ( editDist, options.maxGapOpens, options.maxGapExtens, options.disallowLongDel,
|
|
196 options.disallowIndel, seed, options.maxEditDistSeed, options.threads,
|
|
197 options.mismatchPenalty, options.gapOpenPenalty, options.gapExtensPenalty,
|
|
198 suboptAlign, noIterSearch, color_space, illumina_quals )
|
|
199 if options.genAlignType == 'paired':
|
|
200 gen_alignment_cmds = '-a %s -o %s' % ( options.maxInsertSize, options.maxOccurPairing )
|
|
201 if options.outputTopNDisc:
|
|
202 gen_alignment_cmds += ' -N %s' % options.outputTopNDisc
|
|
203 else:
|
|
204 gen_alignment_cmds = ''
|
|
205 if options.metadata_tsv:
|
|
206 f = open(options.metadata_tsv, 'r')
|
|
207 cols = f.readline().split('\t')
|
2
|
208 readGroup = '@RG\tID:%s\tDS:%s\tPU:%s\tLB:%s\tCN:BMGC\tDT:%s\tFR:%s\tRR:%s\tPL:ILLUMINA\tSM:%s' % ( cols[0], cols[4], cols[16], cols[14], cols[1], cols[19], cols[20], cols[18] )
|
0
|
209 gen_alignment_cmds += ' -r "%s"' % readGroup
|
|
210 print readGroup
|
|
211 if options.rgid:
|
|
212 if not options.rglb or not options.rgpl or not options.rgsm:
|
|
213 stop_err( 'If you want to specify read groups, you must include the ID, LB, PL, and SM tags.' )
|
|
214 readGroup = '@RG\tID:%s\tLB:%s\tPL:%s\tSM:%s' % ( options.rgid, options.rglb, options.rgpl, options.rgsm )
|
|
215 if options.rgcn:
|
|
216 readGroup += '\tCN:%s' % options.rgcn
|
|
217 if options.rgds:
|
|
218 readGroup += '\tDS:%s' % options.rgds
|
|
219 if options.rgdt:
|
|
220 readGroup += '\tDT:%s' % options.rgdt
|
|
221 if options.rgfo:
|
|
222 readGroup += '\tFO:%s' % options.rgfo
|
|
223 if options.rgks:
|
|
224 readGroup += '\tKS:%s' % options.rgks
|
|
225 if options.rgpg:
|
|
226 readGroup += '\tPG:%s' % options.rgpg
|
|
227 if options.rgpi:
|
|
228 readGroup += '\tPI:%s' % options.rgpi
|
|
229 if options.rgpu:
|
|
230 readGroup += '\tPU:%s' % options.rgpu
|
|
231 gen_alignment_cmds += ' -r "%s"' % readGroup
|
|
232 if options.outputTopN:
|
|
233 gen_alignment_cmds += ' -n %s' % options.outputTopN
|
|
234 # set up output files
|
|
235 tmp_align_out = tempfile.NamedTemporaryFile( dir=tmp_dir )
|
|
236 tmp_align_out_name = tmp_align_out.name
|
|
237 tmp_align_out.close()
|
|
238 tmp_align_out2 = tempfile.NamedTemporaryFile( dir=tmp_dir )
|
|
239 tmp_align_out2_name = tmp_align_out2.name
|
|
240 tmp_align_out2.close()
|
|
241 # prepare actual aligning and generate aligning commands
|
|
242 cmd2 = 'bwa aln %s %s %s > %s' % ( aligning_cmds, ref_file_name, fastq, tmp_align_out_name )
|
|
243 cmd2b = ''
|
|
244 if options.genAlignType == 'paired':
|
|
245 cmd2b = 'bwa aln %s %s %s > %s' % ( aligning_cmds, ref_file_name, rfastq, tmp_align_out2_name )
|
|
246 cmd3 = 'bwa sampe %s %s %s %s %s %s >> %s' % ( gen_alignment_cmds, ref_file_name, tmp_align_out_name, tmp_align_out2_name, fastq, rfastq, options.output )
|
|
247 else:
|
|
248 cmd3 = 'bwa samse %s %s %s %s >> %s' % ( gen_alignment_cmds, ref_file_name, tmp_align_out_name, fastq, options.output )
|
|
249 # perform alignments
|
|
250 buffsize = 1048576
|
|
251 try:
|
|
252 # need to nest try-except in try-finally to handle 2.4
|
|
253 try:
|
|
254 # align
|
|
255 try:
|
|
256 tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name
|
|
257 tmp_stderr = open( tmp, 'wb' )
|
|
258 proc = subprocess.Popen( args=cmd2, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() )
|
|
259 returncode = proc.wait()
|
|
260 tmp_stderr.close()
|
|
261 # get stderr, allowing for case where it's very large
|
|
262 tmp_stderr = open( tmp, 'rb' )
|
|
263 stderr = ''
|
|
264 try:
|
|
265 while True:
|
|
266 stderr += tmp_stderr.read( buffsize )
|
|
267 if not stderr or len( stderr ) % buffsize != 0:
|
|
268 break
|
|
269 except OverflowError:
|
|
270 pass
|
|
271 tmp_stderr.close()
|
|
272 if returncode != 0:
|
|
273 raise Exception, stderr
|
|
274 except Exception, e:
|
|
275 raise Exception, 'Error aligning sequence. ' + str( e )
|
|
276 # and again if paired data
|
|
277 try:
|
|
278 if cmd2b:
|
|
279 tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name
|
|
280 tmp_stderr = open( tmp, 'wb' )
|
|
281 proc = subprocess.Popen( args=cmd2b, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() )
|
|
282 returncode = proc.wait()
|
|
283 tmp_stderr.close()
|
|
284 # get stderr, allowing for case where it's very large
|
|
285 tmp_stderr = open( tmp, 'rb' )
|
|
286 stderr = ''
|
|
287 try:
|
|
288 while True:
|
|
289 stderr += tmp_stderr.read( buffsize )
|
|
290 if not stderr or len( stderr ) % buffsize != 0:
|
|
291 break
|
|
292 except OverflowError:
|
|
293 pass
|
|
294 tmp_stderr.close()
|
|
295 if returncode != 0:
|
|
296 raise Exception, stderr
|
|
297 except Exception, e:
|
|
298 raise Exception, 'Error aligning second sequence. ' + str( e )
|
|
299 # generate align
|
|
300 try:
|
|
301 tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name
|
|
302 tmp_stderr = open( tmp, 'wb' )
|
|
303 proc = subprocess.Popen( args=cmd3, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() )
|
|
304 returncode = proc.wait()
|
|
305 tmp_stderr.close()
|
|
306 # get stderr, allowing for case where it's very large
|
|
307 tmp_stderr = open( tmp, 'rb' )
|
|
308 stderr = ''
|
|
309 try:
|
|
310 while True:
|
|
311 stderr += tmp_stderr.read( buffsize )
|
|
312 if not stderr or len( stderr ) % buffsize != 0:
|
|
313 break
|
|
314 except OverflowError:
|
|
315 pass
|
|
316 tmp_stderr.close()
|
|
317 if returncode != 0:
|
|
318 raise Exception, stderr
|
|
319 except Exception, e:
|
|
320 raise Exception, 'Error generating alignments. ' + str( e )
|
|
321 # remove header if necessary
|
|
322 if options.suppressHeader == 'true':
|
|
323 tmp_out = tempfile.NamedTemporaryFile( dir=tmp_dir)
|
|
324 tmp_out_name = tmp_out.name
|
|
325 tmp_out.close()
|
|
326 try:
|
|
327 shutil.move( options.output, tmp_out_name )
|
|
328 except Exception, e:
|
|
329 raise Exception, 'Error moving output file before removing headers. ' + str( e )
|
|
330 fout = file( options.output, 'w' )
|
|
331 for line in file( tmp_out.name, 'r' ):
|
|
332 if not ( line.startswith( '@HD' ) or line.startswith( '@SQ' ) or line.startswith( '@RG' ) or line.startswith( '@PG' ) or line.startswith( '@CO' ) ):
|
|
333 fout.write( line )
|
|
334 fout.close()
|
|
335 # check that there are results in the output file
|
|
336 if os.path.getsize( options.output ) > 0:
|
|
337 sys.stdout.write( 'BWA run on %s-end data' % options.genAlignType )
|
|
338 else:
|
|
339 raise Exception, 'The output file is empty. You may simply have no matches, or there may be an error with your input file or settings.'
|
|
340 except Exception, e:
|
|
341 stop_err( 'The alignment failed.\n' + str( e ) )
|
|
342 finally:
|
|
343 # clean up temp dir
|
|
344 if os.path.exists( tmp_index_dir ):
|
|
345 shutil.rmtree( tmp_index_dir )
|
|
346 if os.path.exists( tmp_dir ):
|
|
347 shutil.rmtree( tmp_dir )
|
|
348
|
|
349 if __name__=="__main__": __main__()
|