0
|
1 #!/usr/bin/env python
|
|
2
|
|
3 import argparse
|
|
4 import os
|
|
5 import shutil
|
|
6 import subprocess
|
|
7 import sys
|
|
8 import shlex
|
|
9 import tempfile
|
|
10 import fileinput
|
|
11 import fileinput
|
|
12 from glob import glob
|
|
13
|
|
14 def stop_err( msg ):
|
|
15 sys.stderr.write( "%s\n" % msg )
|
|
16 sys.exit()
|
|
17
|
|
18 def __main__():
|
|
19
|
|
20 print 'tempfile_location',tempfile.gettempdir()
|
|
21 #Parse Command Line
|
|
22 parser = argparse.ArgumentParser(description='Wrapper for the bismark bisulfite mapper.')
|
|
23 parser.add_argument( '-p', '--num-threads', dest='num_threads',
|
|
24 type=int, default=4, help='Use this many threads to align reads. The default is 4.' )
|
|
25
|
|
26 parser.add_argument( '--bismark_path', dest='bismark_path', help='Path to the bismark perl scripts' )
|
|
27
|
|
28 parser.add_argument( '--bowtie2', action='store_true', default=False, help='Running bismark with bowtie2 and not with bowtie.' )
|
|
29
|
|
30 # input options
|
|
31 parser.add_argument( '--own-file', dest='own_file', help='' )
|
|
32 parser.add_argument( '-D', '--indexes-path', dest='index_path', help='Indexes directory; location of .ebwt and .fa files.' )
|
|
33 parser.add_argument( '-O', '--output', dest='output' )
|
|
34
|
|
35
|
|
36 parser.add_argument( '--output-report-file', dest='output_report_file' )
|
|
37 parser.add_argument( '--suppress-header', dest='suppress_header', action="store_true" )
|
|
38
|
|
39 parser.add_argument( '--mate-paired', dest='mate_paired', action='store_true', help='Reads are mate-paired', default=False)
|
|
40
|
|
41
|
|
42 parser.add_argument( '-1', '--mate1', dest='mate1',
|
|
43 help='The forward reads file in Sanger FASTQ or FASTA format.' )
|
|
44 parser.add_argument( '-2', '--mate2', dest='mate2',
|
|
45 help='The reverse reads file in Sanger FASTQ or FASTA format.' )
|
3
|
46 parser.add_argument( '--sort-bam', dest='sort_bam', action="store_true" )
|
0
|
47
|
|
48 parser.add_argument( '--output-unmapped-reads', dest='output_unmapped_reads',
|
|
49 help='Additional output file with unmapped reads (single-end).' )
|
|
50 parser.add_argument( '--output-unmapped-reads-l', dest='output_unmapped_reads_l',
|
|
51 help='File name for unmapped reads (left, paired-end).' )
|
|
52 parser.add_argument( '--output-unmapped-reads-r', dest='output_unmapped_reads_r',
|
|
53 help='File name for unmapped reads (right, paired-end).' )
|
|
54
|
|
55
|
|
56 parser.add_argument( '--output-suppressed-reads', dest='output_suppressed_reads',
|
|
57 help='Additional output file with suppressed reads (single-end).' )
|
|
58 parser.add_argument( '--output-suppressed-reads-l', dest='output_suppressed_reads_l',
|
|
59 help='File name for suppressed reads (left, paired-end).' )
|
|
60 parser.add_argument( '--output-suppressed-reads-r', dest='output_suppressed_reads_r',
|
|
61 help='File name for suppressed reads (right, paired-end).' )
|
|
62 parser.add_argument( '--stdout', dest='output_stdout',
|
|
63 help='File name for the standard output of bismark.' )
|
|
64
|
|
65
|
|
66 parser.add_argument( '--single-paired', dest='single_paired',
|
|
67 help='The single-end reads file in Sanger FASTQ or FASTA format.' )
|
|
68
|
|
69 parser.add_argument( '--fastq', action='store_true', help='Query filetype is in FASTQ format')
|
|
70 parser.add_argument( '--fasta', action='store_true', help='Query filetype is in FASTA format')
|
|
71 parser.add_argument( '--phred64-quals', dest='phred64', action="store_true" )
|
|
72
|
|
73
|
|
74 parser.add_argument( '--skip-reads', dest='skip_reads', type=int )
|
|
75 parser.add_argument( '--qupto', type=int)
|
|
76
|
|
77
|
|
78 # paired end options
|
|
79 parser.add_argument( '-I', '--minins', dest='min_insert' )
|
|
80 parser.add_argument( '-X', '--maxins', dest='max_insert' )
|
|
81 parser.add_argument( '--no-mixed', dest='no_mixed', action="store_true" )
|
|
82 parser.add_argument( '--no-discordant', dest='no_discordant', action="store_true" )
|
|
83
|
|
84 #parse general options
|
|
85 # default 20
|
|
86 parser.add_argument( '--seed-len', dest='seed_len', type=int)
|
|
87 # default 15
|
|
88 parser.add_argument( '--seed-extention-attempts', dest='seed_extention_attempts', type=int )
|
|
89 # default 0
|
|
90 parser.add_argument( '--seed-mismatches', dest='seed_mismatches', type=int )
|
|
91 # default 2
|
|
92 parser.add_argument( '--max-reseed', dest='max_reseed', type=int )
|
|
93 """
|
|
94 # default 70
|
|
95 parser.add_argument( '--maqerr', dest='maqerr', type=int )
|
|
96 """
|
|
97
|
|
98 """
|
|
99 The number of megabytes of memory a given thread is given to store path
|
|
100 descriptors in --best mode. Best-first search must keep track of many paths
|
|
101 at once to ensure it is always extending the path with the lowest cumulative
|
|
102 cost. Bowtie tries to minimize the memory impact of the descriptors, but
|
|
103 they can still grow very large in some cases. If you receive an error message
|
|
104 saying that chunk memory has been exhausted in --best mode, try adjusting
|
|
105 this parameter up to dedicate more memory to the descriptors. Default: 512.
|
|
106 """
|
|
107 parser.add_argument( '--chunkmbs', type=int, default=512 )
|
|
108
|
|
109 args = parser.parse_args()
|
|
110
|
|
111 # Create bismark index if necessary.
|
|
112 index_dir = ""
|
|
113 if args.own_file:
|
|
114 """
|
|
115 Create a temporary index with the offered files from the user.
|
|
116 Utilizing the script: bismark_genome_preparation
|
|
117 bismark_genome_preparation --bowtie2 hg19/
|
|
118 """
|
|
119 tmp_index_dir = tempfile.mkdtemp()
|
|
120 index_path = os.path.join( tmp_index_dir, '.'.join( os.path.split( args.own_file )[1].split( '.' )[:-1] ) )
|
|
121 try:
|
|
122 """
|
|
123 Create a hard link pointing to args.own_file named 'index_path'.fa.
|
|
124 """
|
|
125 os.symlink( args.own_file, index_path + '.fa' )
|
|
126 except Exception, e:
|
|
127 if os.path.exists( tmp_index_dir ):
|
|
128 shutil.rmtree( tmp_index_dir )
|
|
129 stop_err( 'Error in linking the reference database.\n' + str( e ) )
|
|
130 # bismark_genome_preparation needs the complete path to the folder in which the database is stored
|
|
131 if args.bowtie2:
|
|
132 cmd_index = 'bismark_genome_preparation --bowtie2 %s ' % ( tmp_index_dir )
|
|
133 else:
|
|
134 cmd_index = 'bismark_genome_preparation %s ' % ( tmp_index_dir )
|
|
135 if args.bismark_path:
|
|
136 if os.path.exists(args.bismark_path):
|
|
137 # add the path to the bismark perl scripts, that is needed for galaxy
|
|
138 cmd_index = os.path.join(args.bismark_path, cmd_index)
|
|
139 else:
|
|
140 # assume the same directory as that script
|
|
141 cmd_index = 'perl %s' % os.path.join(os.path.realpath(os.path.dirname(__file__)), cmd_index)
|
|
142 try:
|
|
143 tmp = tempfile.NamedTemporaryFile( dir=tmp_index_dir ).name
|
|
144 tmp_stderr = open( tmp, 'wb' )
|
|
145 proc = subprocess.Popen( args=cmd_index, shell=True, cwd=tmp_index_dir, stdout=open(os.devnull, 'wb'), stderr=tmp_stderr.fileno() )
|
|
146 returncode = proc.wait()
|
|
147 tmp_stderr.close()
|
|
148 # get stderr, allowing for case where it's very large
|
|
149 tmp_stderr = open( tmp, 'rb' )
|
|
150 stderr = ''
|
|
151 buffsize = 1048576
|
|
152 try:
|
|
153 while True:
|
|
154 stderr += tmp_stderr.read( buffsize )
|
|
155 if not stderr or len( stderr ) % buffsize != 0:
|
|
156 break
|
|
157 except OverflowError:
|
|
158 pass
|
|
159 tmp_stderr.close()
|
|
160 if returncode != 0:
|
|
161 raise Exception, stderr
|
|
162 except Exception, e:
|
|
163 if os.path.exists( tmp_index_dir ):
|
|
164 shutil.rmtree( tmp_index_dir )
|
|
165 stop_err( 'Error indexing reference sequence\n' + str( e ) )
|
|
166 index_dir = tmp_index_dir
|
|
167 else:
|
|
168 # bowtie path is the path to the index directory and the first path of the index file name
|
|
169 index_dir = os.path.dirname( args.index_path )
|
|
170
|
|
171 # Build bismark command
|
|
172
|
|
173 """
|
|
174 Bismark requires a large amount of temporary disc space. If that is not available, for example on a cluster you can hardcode the
|
|
175 TMP to some larger space. It's not recommended but it works.
|
|
176 """
|
|
177 #tmp_bismark_dir = tempfile.mkdtemp( dir='/data/0/galaxy_db/tmp/' )
|
|
178 tmp_bismark_dir = tempfile.mkdtemp()
|
|
179 output_dir = os.path.join( tmp_bismark_dir, 'results')
|
3
|
180 cmd = 'bismark %(args)s --bam --temp_dir %(tmp_bismark_dir)s --gzip -o %(output_dir)s --quiet %(genome_folder)s %(reads)s'
|
0
|
181
|
|
182 if args.fasta:
|
3
|
183 # the query input files (specified as mate1,mate2 or singles) are FastA
|
0
|
184 cmd = '%s %s' % (cmd, '--fasta')
|
|
185 elif args.fastq:
|
|
186 cmd = '%s %s' % (cmd, '--fastq')
|
|
187
|
|
188 if args.bismark_path:
|
|
189 # add the path to the bismark perl scripts, that is needed for galaxy
|
|
190 if os.path.exists(args.bismark_path):
|
|
191 cmd = os.path.join(args.bismark_path, cmd)
|
|
192 else:
|
|
193 # assume the same directory as that script
|
|
194 cmd = 'perl %s' % os.path.join(os.path.realpath(os.path.dirname(__file__)), cmd)
|
|
195
|
|
196 arguments = {
|
|
197 'genome_folder': index_dir,
|
|
198 'args': '',
|
|
199 'tmp_bismark_dir': tmp_bismark_dir,
|
|
200 'output_dir': output_dir,
|
|
201 }
|
|
202
|
|
203 additional_opts = ''
|
|
204 # Set up the reads
|
|
205 if args.mate_paired:
|
|
206 # paired-end reads library
|
|
207 reads = '-1 %s ' % ( args.mate1 )
|
|
208 reads += ' -2 %s ' % ( args.mate2 )
|
|
209 additional_opts += ' -I %s -X %s ' % (args.min_insert, args.max_insert)
|
|
210 else:
|
|
211 # single paired reads library
|
|
212 reads = ' %s ' % ( args.single_paired )
|
|
213
|
|
214
|
|
215 if not args.bowtie2:
|
|
216 # use bowtie specific options
|
|
217 #additional_opts += ' --best ' # bug in bismark, --best is not available as option. Only --non-best, best-mode is activated by default
|
|
218 if args.seed_mismatches:
|
|
219 # --seedmms
|
|
220 additional_opts += ' -n %s ' % args.seed_mismatches
|
|
221 if args.seed_len:
|
|
222 # --seedlen
|
|
223 additional_opts += ' -l %s ' % args.seed_len
|
|
224
|
|
225 # alignment options
|
|
226 if args.bowtie2:
|
3
|
227 additional_opts += ' -p %s --bowtie2 ' % (int(args.num_threads/2)) #divides by 2 here since bismark will spawn 2 (original top and original bottom) jobs with -p threads each
|
0
|
228 if args.seed_mismatches:
|
|
229 additional_opts += ' -N %s ' % args.seed_mismatches
|
|
230 if args.seed_len:
|
|
231 additional_opts += ' -L %s ' % args.seed_len
|
|
232 if args.seed_extention_attempts:
|
|
233 additional_opts += ' -D %s ' % args.seed_extention_attempts
|
|
234 if args.max_reseed:
|
|
235 additional_opts += ' -R %s ' % args.max_reseed
|
|
236 if args.no_discordant:
|
|
237 additional_opts += ' --no-discordant '
|
|
238 if args.no_mixed:
|
|
239 additional_opts += ' --no-mixed '
|
|
240 """
|
|
241 if args.maqerr:
|
|
242 additional_opts += ' --maqerr %s ' % args.maqerr
|
|
243 """
|
|
244 if args.skip_reads:
|
|
245 additional_opts += ' --skip %s ' % args.skip_reads
|
|
246 if args.qupto:
|
|
247 additional_opts += ' --qupto %s ' % args.qupto
|
|
248 if args.phred64:
|
|
249 additional_opts += ' --phred64-quals '
|
|
250 if args.suppress_header:
|
|
251 additional_opts += ' --sam-no-hd '
|
|
252 if args.output_unmapped_reads or ( args.output_unmapped_reads_l and args.output_unmapped_reads_r):
|
|
253 additional_opts += ' --un '
|
|
254 if args.output_suppressed_reads or ( args.output_suppressed_reads_l and args.output_suppressed_reads_r):
|
|
255 additional_opts += ' --ambiguous '
|
|
256
|
|
257 arguments.update( {'args': additional_opts, 'reads': reads} )
|
|
258
|
|
259 # Final bismark command:
|
|
260 cmd = cmd % arguments
|
|
261 print 'bismark_cmd:', cmd
|
|
262 #sys.stderr.write( cmd )
|
|
263 #sys.exit(1)
|
|
264 # Run
|
|
265 try:
|
|
266 tmp_out = tempfile.NamedTemporaryFile().name
|
|
267 tmp_stdout = open( tmp_out, 'wb' )
|
|
268 tmp_err = tempfile.NamedTemporaryFile().name
|
|
269 tmp_stderr = open( tmp_err, 'wb' )
|
|
270 proc = subprocess.Popen( args=cmd, shell=True, cwd=".", stdout=tmp_stdout, stderr=tmp_stderr )
|
|
271 returncode = proc.wait()
|
|
272
|
|
273 if returncode != 0:
|
|
274 tmp_stdout.close()
|
|
275 tmp_stderr.close()
|
|
276 # get stderr, allowing for case where it's very large
|
|
277 tmp_stderr = open( tmp_err, 'rb' )
|
|
278 stderr = ''
|
|
279 buffsize = 1048576
|
|
280 try:
|
|
281 while True:
|
|
282 stderr += tmp_stderr.read( buffsize )
|
|
283 if not stderr or len( stderr ) % buffsize != 0:
|
|
284 break
|
|
285 except OverflowError:
|
|
286 pass
|
|
287
|
|
288 raise Exception, stderr
|
|
289 tmp_stdout.close()
|
|
290 tmp_stderr.close()
|
|
291
|
|
292 # TODO: look for errors in program output.
|
|
293 except Exception, e:
|
|
294 stop_err( 'Error in bismark:\n' + str( e ) )
|
|
295
|
|
296 # collect and copy output files
|
|
297 if args.output_report_file:
|
|
298 output_report_file = open(args.output_report_file, 'w+')
|
|
299 for line in fileinput.input(glob( os.path.join( output_dir, '*report.txt') )):
|
|
300 output_report_file.write(line)
|
|
301 output_report_file.close()
|
|
302
|
|
303
|
|
304 if args.output_suppressed_reads:
|
|
305 shutil.move( glob(os.path.join( output_dir, '*ambiguous_reads.txt'))[0], args.output_suppressed_reads )
|
|
306 if args.output_suppressed_reads_l:
|
|
307 shutil.move( glob(os.path.join( output_dir, '*ambiguous_reads_1.txt'))[0], args.output_suppressed_reads_l )
|
|
308 if args.output_suppressed_reads_r:
|
|
309 shutil.move( glob(os.path.join( output_dir, '*ambiguous_reads_2.txt'))[0], args.output_suppressed_reads_r )
|
|
310
|
|
311 if args.output_unmapped_reads:
|
|
312 shutil.move( glob(os.path.join( output_dir, '*unmapped_reads.txt'))[0], args.output_unmapped_reads )
|
|
313 if args.output_unmapped_reads_l:
|
|
314 shutil.move( glob(os.path.join( output_dir, '*unmapped_reads_1.txt'))[0], args.output_unmapped_reads_l )
|
|
315 if args.output_unmapped_reads_r:
|
|
316 shutil.move( glob(os.path.join( output_dir, '*unmapped_reads_2.txt'))[0], args.output_unmapped_reads_r )
|
|
317
|
|
318 try:
|
|
319 """
|
|
320 merge all bam files
|
|
321 """
|
|
322 #tmp_out = tempfile.NamedTemporaryFile( dir=output_dir ).name
|
|
323 tmp_stdout = open( tmp_out, 'wab' )
|
|
324 tmp_err = tempfile.NamedTemporaryFile( dir=output_dir ).name
|
|
325 tmp_stderr = open( tmp_err, 'wb' )
|
|
326
|
|
327 tmp_res = tempfile.NamedTemporaryFile( dir= output_dir).name
|
|
328
|
|
329 bam_files = glob( os.path.join( output_dir, '*.bam') )
|
|
330 if len( bam_files ) > 1:
|
3
|
331 cmd = 'samtools merge -@ %s -f %s %s ' % ( args.num_threads, tmp_res, ' '.join( bam_files ) )
|
0
|
332
|
3
|
333 proc = subprocess.Popen( args=shlex.split( cmd ), stdout=subprocess.PIPE )
|
0
|
334
|
3
|
335 returncode = proc.wait()
|
|
336 tmp_stdout.close()
|
|
337 tmp_stderr.close()
|
|
338 if returncode != 0:
|
|
339 raise Exception, open( tmp_stderr.name ).read()
|
|
340 else:
|
|
341 tmp_res = bam_files[0]
|
0
|
342
|
3
|
343 bam_path = "%s" % tmp_res
|
|
344
|
0
|
345 if os.path.exists( bam_path ):
|
3
|
346 if args.sort_bam:
|
|
347 cmd = 'samtools sort -@ %s %s %s' % (args.num_threads, bam_path, args.output)
|
|
348 else:
|
|
349 shutil.copy( bam_path, args.output )
|
0
|
350 else:
|
|
351 stop_err( 'BAM file no found:\n' + str( bam_path ) )
|
3
|
352
|
|
353
|
0
|
354
|
|
355 # TODO: look for errors in program output.
|
|
356 except Exception, e:
|
|
357 stop_err( 'Error in merging bam files:\n' + str( e ) )
|
|
358
|
|
359
|
|
360 if args.output_stdout:
|
|
361 # copy the temporary saved stdout from bismark
|
|
362 shutil.move( tmp_out, args.output_stdout )
|
|
363
|
|
364 # Clean up temp dirs
|
|
365 if args.own_file:
|
|
366 if os.path.exists( tmp_index_dir ):
|
|
367 shutil.rmtree( tmp_index_dir )
|
|
368 if os.path.exists( tmp_bismark_dir ):
|
|
369 shutil.rmtree( tmp_bismark_dir )
|
|
370 if os.path.exists( output_dir ):
|
|
371 shutil.rmtree( output_dir )
|
|
372
|
|
373 if __name__=="__main__": __main__()
|