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