1
|
1 #!/usr/bin/env python
|
0
|
2
|
|
3 from optparse import OptionParser, OptionGroup
|
|
4 import re
|
|
5 import tempfile
|
|
6 from bs_align import output
|
|
7 from bs_align.bs_pair_end import *
|
|
8 from bs_align.bs_single_end import *
|
|
9 from bs_align.bs_rrbs import *
|
1
|
10 #import re
|
|
11 #from bs_utils.utils import *
|
0
|
12
|
|
13
|
|
14 if __name__ == '__main__':
|
|
15
|
1
|
16 parser = OptionParser(usage="Usage: %prog {-i <single> | -1 <mate1> -2 <mate2>} -g <genome.fa> [options]")
|
0
|
17 # option group 1
|
|
18 opt_group = OptionGroup(parser, "For single end reads")
|
1
|
19 opt_group.add_option("-i", "--input", type="string", dest="infilename",help="Input read file (FORMAT: sequences, qseq, fasta, fastq). Ex: read.fa or read.fa.gz", metavar="INFILE")
|
0
|
20 parser.add_option_group(opt_group)
|
|
21
|
|
22 # option group 2
|
|
23 opt_group = OptionGroup(parser, "For pair end reads")
|
1
|
24 opt_group.add_option("-1", "--input_1", type="string", dest="infilename_1",help="Input read file, mate 1 (FORMAT: sequences, qseq, fasta, fastq)", metavar="FILE")
|
|
25 opt_group.add_option("-2", "--input_2", type="string", dest="infilename_2",help="Input read file, mate 2 (FORMAT: sequences, qseq, fasta, fastq)", metavar="FILE")
|
|
26 opt_group.add_option("-I", "--minins",type = "int",dest = "min_insert_size", help="The minimum insert size for valid paired-end alignments [Default: %default]", default = 0)
|
|
27 opt_group.add_option("-X", "--maxins",type = "int",dest = "max_insert_size", help="The maximum insert size for valid paired-end alignments [Default: %default]", default = 500)
|
0
|
28 parser.add_option_group(opt_group)
|
|
29
|
|
30 # option group 3
|
|
31 opt_group = OptionGroup(parser, "Reduced Representation Bisulfite Sequencing Options")
|
1
|
32 opt_group.add_option("-r", "--rrbs", action="store_true", dest="rrbs", default = False, help = 'Map reads to the Reduced Representation genome')
|
0
|
33 opt_group.add_option("-c", "--cut-site", type="string",dest="cut_format", help="Cutting sites of restriction enzyme. Ex: MspI(C-CGG), Mael:(C-TAG), double-enzyme MspI&Mael:(C-CGG,C-TAG). [Default: %default]", metavar="pattern", default = "C-CGG")
|
1
|
34 opt_group.add_option("-L", "--low", type = "int", dest="rrbs_low_bound", help="Lower bound of fragment length (excluding C-CGG ends) [Default: %default]", default = 20)
|
|
35 opt_group.add_option("-U", "--up", type = "int", dest="rrbs_up_bound", help="Upper bound of fragment length (excluding C-CGG ends) [Default: %default]", default = 500)
|
0
|
36 parser.add_option_group(opt_group)
|
|
37
|
|
38 # option group 4
|
|
39 opt_group = OptionGroup(parser, "General options")
|
|
40 opt_group.add_option("-t", "--tag", type="string", dest="taginfo",help="[Y]es for undirectional lib, [N]o for directional [Default: %default]", metavar="TAG", default = 'N')
|
1
|
41 opt_group.add_option("-s","--start_base",type = "int",dest = "cutnumber1", help="The first cycle of the read to be mapped [Default: %default]", default = 1)
|
|
42 opt_group.add_option("-e","--end_base",type = "int",dest = "cutnumber2", help="The last cycle of the read to be mapped [Default: %default]", default = 200)
|
|
43 opt_group.add_option("-a", "--adapter", type="string", dest="adapter_file",help="Input text file of your adaptor sequences (to be trimmed from the 3'end of the reads, ). "
|
|
44 "Input one seq for dir. lib., twon seqs for undir. lib. One line per sequence. "
|
|
45 "Only the first 10bp will be used", metavar="FILE", default = '')
|
|
46 opt_group.add_option("--am",type = "int",dest = "adapter_mismatch", help="Number of mismatches allowed in adapter [Default: %default]", default = 0)
|
|
47 opt_group.add_option("-g", "--genome", type="string", dest="genome",help="Name of the reference genome (should be the same as \"-f\" in bs_seeker2-build.py ) [ex. chr21_hg18.fa]")
|
|
48 opt_group.add_option("-m", "--mismatches",type = "float", dest="no_mismatches",help="Number of mismatches in one read [Default: %default]", default = 4)
|
|
49 opt_group.add_option("--aligner", dest="aligner",help="Aligner program for short reads mapping: " + ', '.join(supported_aligners) + " [Default: %default]", metavar="ALIGNER", default = BOWTIE)
|
|
50 opt_group.add_option("-p", "--path", dest="aligner_path", help="Path to the aligner program. Detected: " +' '*70+ '\t'.join(('%s: %s '+' '*70) % (al, aligner_path[al]) for al in sorted(supported_aligners)),
|
0
|
51 metavar="PATH"
|
|
52 )
|
|
53 opt_group.add_option("-d", "--db", type="string", dest="dbpath",help="Path to the reference genome library (generated in preprocessing genome) [Default: %default]" , metavar="DBPATH", default = reference_genome_path)
|
|
54 opt_group.add_option("-l", "--split_line",type = "int", dest="no_split",help="Number of lines per split (the read file will be split into small files for mapping. The result will be merged. [Default: %default]", default = 4000000)
|
|
55 opt_group.add_option("-o", "--output", type="string", dest="outfilename",help="The name of output file [INFILE.bs(se|pe|rrbs)]", metavar="OUTFILE")
|
|
56 opt_group.add_option("-f", "--output-format", type="string", dest="output_format",help="Output format: "+', '.join(output.formats)+" [Default: %default]", metavar="FORMAT", default = output.BAM)
|
|
57 opt_group.add_option("--no-header", action="store_true", dest="no_SAM_header",help="Suppress SAM header lines [Default: %default]", default = False)
|
1
|
58 opt_group.add_option("--temp_dir", type="string", dest="temp_dir",help="The path to your temporary directory [Detected: %default]", metavar="PATH", default = tempfile.gettempdir())
|
0
|
59 opt_group.add_option("--XS",type = "string", dest="XS_filter",help="Filter definition for tag XS, format X,Y. X=0.8 and y=5 indicate that for one read, if #(mCH sites)/#(all CH sites)>0.8 and #(mCH sites)>5, then tag XS=1; or else tag XS=0. [Default: %default]", default = "0.5,5") # added by weilong
|
|
60 opt_group.add_option("--multiple-hit", action="store_true", dest="Output_multiple_hit", default = False, help = 'Output reads with multiple hits to file\"Multiple_hit.fa\"')
|
|
61
|
|
62 opt_group.add_option("-v", "--version", action="store_true", dest="version",help="show version of BS-Seeker2", metavar="version", default = False)
|
|
63
|
|
64 parser.add_option_group(opt_group)
|
|
65
|
|
66 # option group 5
|
|
67 opt_group = OptionGroup(parser, "Aligner Options",
|
|
68 "You may specify any additional options for the aligner. You just have to prefix them with " +
|
|
69 ', '.join('%s for %s' % (aligner_options_prefixes[aligner], aligner) for aligner in supported_aligners)+
|
|
70 ', and BS Seeker will pass them on. For example: --bt-p 4 will increase the number of threads for bowtie to 4, '
|
|
71 '--bt--tryhard will instruct bowtie to try as hard as possible to find valid alignments when they exist, and so on. '
|
|
72 'Be sure that you know what you are doing when using these options! Also, we don\'t do any validation on the values.')
|
|
73 parser.add_option_group(opt_group)
|
|
74
|
|
75
|
|
76 #----------------------------------------------------------------
|
|
77 # separate aligner options from BS Seeker options
|
|
78 aligner_options = {}
|
|
79 bs_seeker_options = []
|
|
80 i = 1
|
|
81 while i < len(sys.argv):
|
|
82 arg = sys.argv[i]
|
|
83 m = re.match(r'^%s' % '|'.join('(%s)'% aligner_options_prefixes[al] for al in supported_aligners), arg)
|
|
84 if m:
|
|
85 a_opt = arg.replace(m.group(0),'-',1)
|
|
86 aligner_options[a_opt] = []
|
|
87 while i + 1 < len(sys.argv) and sys.argv[i+1][0] != '-':
|
|
88 aligner_options[a_opt].append(sys.argv[i+1])
|
|
89 i += 1
|
|
90 if len(aligner_options[a_opt]) == 0: # if it is a key-only option
|
|
91 aligner_options[a_opt] = True
|
|
92 else:
|
|
93 bs_seeker_options.append(arg)
|
|
94 i += 1
|
|
95
|
|
96
|
|
97 (options, args) = parser.parse_args(args = bs_seeker_options)
|
|
98
|
|
99
|
|
100 # if no options were given by the user, print help and exit
|
|
101 if len(sys.argv) == 1:
|
1
|
102 parser.print_help()
|
0
|
103 exit(0)
|
|
104
|
|
105 if options.version :
|
|
106 show_version()
|
|
107 exit (-1)
|
|
108 else :
|
|
109 show_version()
|
|
110
|
|
111 # check parameters
|
|
112 # input read files
|
|
113 if options.infilename and (options.infilename_1 or options.infilename_2):
|
|
114 error('-i and [-1|-2] options are exclusive. You should use only one of them.')
|
|
115
|
|
116 if not (options.infilename or (options.infilename_1 and options.infilename_2)):
|
|
117 error('You should set either -i or -1 and -2 options.')
|
1
|
118
|
|
119 # Calculate the length of read
|
|
120 if options.infilename :
|
|
121 read_file = options.infilename
|
|
122 elif options.infilename_1 :
|
|
123 read_file = options.infilename_1
|
|
124 else :
|
|
125 error('You should at least specify -i or -1 options.')
|
|
126
|
|
127 try :
|
|
128 if read_file.endswith(".gz") : # support input file ending with ".gz"
|
|
129 read_inf = gzip.open(read_file, "rb")
|
|
130 else :
|
|
131 read_inf=open(read_file,"r")
|
|
132 except IOError :
|
|
133 print "[Error] Cannot open input file : %s" % read_file
|
|
134 exit(-1)
|
|
135 oneline = read_inf.readline()
|
|
136 oneline = read_inf.readline() # get the second line
|
|
137 read_len = min(len(oneline), (options.cutnumber2-options.cutnumber1))
|
|
138 read_inf.close()
|
|
139 # mismatch allowed: bowtie 1,build-in parameter '-m'; bowtie 2, post-filter paramter
|
|
140 # mismatch should no greater than the read length
|
|
141 no_mismatches = float(options.no_mismatches)
|
|
142 if (no_mismatches < 1) :
|
|
143 int_no_mismatches=int(no_mismatches * read_len)
|
|
144 else :
|
|
145 int_no_mismatches=int(no_mismatches)
|
|
146
|
|
147 str_no_mismatches=str(options.no_mismatches) # pass to specific mode
|
|
148
|
|
149
|
0
|
150 # -t, directional / un-directional library
|
|
151 asktag=str(options.taginfo).upper()
|
|
152 if asktag not in 'YN':
|
|
153 error('-t option should be either Y or N, not %s' % asktag)
|
|
154 # -a
|
|
155 if options.aligner not in supported_aligners:
|
|
156 error('-a option should be: %s' % ' ,'.join(supported_aligners)+'.')
|
|
157 # path for aligner
|
|
158 aligner_exec = os.path.expanduser( os.path.join(options.aligner_path or aligner_path[options.aligner], options.aligner) )
|
1
|
159
|
|
160
|
0
|
161 # -g
|
|
162 if options.genome is None:
|
|
163 error('-g is a required option')
|
|
164 genome = os.path.split(options.genome)[1]
|
|
165 genome_subdir = genome
|
|
166
|
|
167 # try to guess the location of the reference genome for RRBS
|
|
168 if options.rrbs:
|
|
169 if options.rrbs_low_bound and options.rrbs_up_bound:
|
|
170 if options.cut_format == "C-CGG" :
|
|
171 genome_subdir += '_rrbs_%d_%d' % (options.rrbs_low_bound, options.rrbs_up_bound)
|
|
172 else :
|
|
173 genome_subdir += '_rrbs_%s_%d_%d' % ( re.sub(",","-",re.sub("-", "", options.cut_format)), options.rrbs_low_bound, options.rrbs_up_bound)
|
|
174 else:
|
|
175 possible_refs = filter(lambda dir: dir.startswith(genome+'_rrbs_'), os.listdir(options.dbpath))
|
|
176 if len(possible_refs) == 1:
|
|
177 genome_subdir = possible_refs[0]
|
|
178 else:
|
|
179 error('Cannot localize unambiguously the reference genome for RRBS. '
|
|
180 'Please, specify the options \"--low\" and \"--up\" that you used at the index-building step.\n'
|
|
181 'Possible choices are:\n' + '\n'.join([pr.split('_rrbs_')[-1].replace('_',', ') for pr in possible_refs]))
|
|
182
|
|
183 db_path = os.path.expanduser(os.path.join(options.dbpath, genome_subdir + '_' + options.aligner))
|
|
184
|
1
|
185
|
0
|
186 if not os.path.isdir(db_path):
|
|
187 error('Index DIR \"' + genome_subdir + '..\" cannot be found in ' + options.dbpath +'.\n\tPlease run the bs_seeker2-build.py '
|
|
188 'to create it with the correct parameters for -g, -r, --low, --up and --aligner.')
|
|
189
|
|
190 # default aligner options
|
|
191 aligner_options_defaults = {
|
|
192 BOWTIE : { '-e' : 40*int_no_mismatches,
|
|
193 '--nomaqround' : True,
|
|
194 '--norc' : True,
|
1
|
195 #'-k' : 2,
|
0
|
196 # -k=2; report two best hits, and filter by error rates
|
|
197 '--quiet' : True,
|
|
198 '--best' : True,
|
|
199 # '--suppress' : '2,5,6',
|
|
200 '--sam' : True,
|
|
201 '--sam-nohead' : True,
|
|
202 '-p' : 2
|
|
203 },
|
|
204 BOWTIE2 : {
|
|
205 #'-M' : 5,
|
|
206 '--norc' : True,
|
|
207 '--quiet' : True,
|
|
208 '-p' : 2,
|
|
209 '--sam-nohead' : True,
|
|
210 # run bowtie2 in local mode by default
|
|
211 '--local' : '--end-to-end' not in aligner_options,
|
|
212 #'--mm' : True,
|
1
|
213 #'-k' : 2
|
0
|
214 },
|
|
215 SOAP : { '-v' : int_no_mismatches,
|
|
216 '-p' : 2,
|
|
217 '-r' : 2,
|
|
218 '-M' : 4
|
|
219 },
|
|
220 RMAP : { '-M' : 2
|
|
221 # to do # control for only mapping on + strand
|
|
222 }
|
|
223
|
|
224 }
|
|
225
|
|
226 if '--end-to-end' not in aligner_options:
|
|
227 aligner_options_defaults[BOWTIE2].update({'-D' : 50})
|
|
228 #aligner_options_defaults[BOWTIE2].update({'-D' : 50, '-R': 3, '-N': 0, '-L': 15, '-i' : 'S,1,0.50'})
|
|
229 else:
|
|
230 aligner_options_defaults[BOWTIE2].update({'-D' : 50, '-L': 15, '--score-min': 'L,-0.6,-0.6' })
|
|
231
|
|
232 aligner_options = dict(aligner_options_defaults[options.aligner], **aligner_options)
|
|
233
|
|
234 aligner_options_string = lambda : ' %s ' % (' '.join(opt_key +
|
|
235 (' ' + ' '.join(map(str,opt_val)) # join all values if the value is an array
|
|
236 if type(opt_val) is list else
|
|
237 ('' if type(opt_val) is bool and opt_val # output an empty string if it is a key-only option
|
|
238 else ' ' +str(opt_val)) # output the value if it is a single value
|
|
239 )
|
|
240 for opt_key, opt_val in aligner_options.iteritems() if opt_val not in [None, False]))
|
|
241
|
|
242
|
|
243 # tmp_path = (options.outfilename or options.infilename or options.infilename_1) +'-'+ options.aligner+ '-TMP'
|
|
244 # clear_dir(tmp_path)
|
|
245
|
|
246 if options.output_format not in output.formats:
|
|
247 error('Output format should be one of: ' + ', '.join(output.formats))
|
|
248
|
|
249 if options.outfilename:
|
|
250 outfilename = options.outfilename
|
|
251 logfilename = outfilename
|
|
252 elif options.infilename is not None:
|
|
253 logfilename = options.infilename+'_'+ ('rr' if options.rrbs else '') + 'bsse'
|
|
254 outfilename = logfilename + '.' + options.output_format
|
|
255 else:
|
|
256 logfilename = options.infilename_1+'_'+ ('rr' if options.rrbs else '') + 'bspe'
|
|
257 outfilename = logfilename + '.' + options.output_format
|
|
258
|
|
259 outfilename = os.path.expanduser(outfilename)
|
|
260 logfilename = os.path.expanduser(logfilename)
|
|
261 outfile = output.outfile(outfilename, options.output_format, deserialize(os.path.join(db_path, 'refname')), ' '.join(sys.argv), options.no_SAM_header)
|
|
262
|
|
263 open_log(logfilename+'.bs_seeker2_log')
|
|
264
|
|
265 aligner_title = options.aligner
|
|
266 if options.aligner == BOWTIE2 :
|
|
267 if '--end-to-end' in aligner_options :
|
|
268 aligner_title = aligner_title + "-e2e"
|
|
269 else:
|
|
270 aligner_title = aligner_title + "-local"
|
|
271
|
1
|
272 if options.aligner == BOWTIE :
|
|
273 logm("Mode: Bowtie")
|
|
274 elif options.aligner == BOWTIE2 :
|
|
275 if '--end-to-end' not in aligner_options :
|
|
276 logm("Mode: Bowtie2, local alignment")
|
|
277 else :
|
|
278 logm("Mode: Bowtie2, end-to-end alignment")
|
|
279
|
|
280
|
0
|
281 tmp_path = tempfile.mkdtemp(prefix='bs_seeker2_%s_-%s-TMP-' % (os.path.split(outfilename)[1], aligner_title ), dir = options.temp_dir)
|
|
282
|
|
283
|
|
284 (XS_x, XS_y) = options.XS_filter.split(",")
|
|
285 XS_pct = float(XS_x)
|
|
286 XS_count = int(XS_y)
|
1
|
287 logm('Filter for tag XS: #(mCH)/#(all CH)>%.2f%% and #(mCH)>%d' % (XS_pct*100, XS_count))
|
0
|
288
|
|
289
|
|
290 logm('Temporary directory: %s' % tmp_path)
|
|
291 logm('Reduced Representation Bisulfite Sequencing: %s' % str(options.rrbs))
|
|
292 if options.infilename is not None:
|
|
293 logm('Single end')
|
|
294
|
|
295 aligner_command = aligner_exec + aligner_options_string() + \
|
1
|
296 { BOWTIE : ' -k 2 %(reference_genome)s -f %(input_file)s %(output_file)s',
|
|
297 BOWTIE2 : ' -k 2 -x %(reference_genome)s -f -U %(input_file)s -S %(output_file)s',
|
0
|
298 SOAP : ' -D %(reference_genome)s.fa.index -o %(output_file)s -a %(input_file)s',
|
|
299 RMAP : ' -c %(reference_genome)s.fa -o %(output_file)s %(input_file)s'
|
|
300 }[options.aligner]
|
|
301 logm ('Aligner command: %s' % aligner_command)
|
|
302 # single end reads
|
|
303 if options.rrbs: # RRBS scan
|
|
304 bs_rrbs(options.infilename,
|
|
305 asktag,
|
|
306 options.adapter_file,
|
|
307 options.cutnumber1,
|
|
308 options.cutnumber2,
|
|
309 options.no_split,
|
|
310 str_no_mismatches,
|
|
311 aligner_command,
|
|
312 db_path,
|
|
313 tmp_path,
|
|
314 outfile,
|
|
315 XS_pct,
|
|
316 XS_count,
|
|
317 options.adapter_mismatch,
|
|
318 options.cut_format,
|
|
319 options.Output_multiple_hit
|
|
320 )
|
|
321 else: # Normal single end scan
|
|
322 bs_single_end( options.infilename,
|
|
323 asktag,
|
|
324 options.adapter_file,
|
|
325 options.cutnumber1,
|
|
326 options.cutnumber2,
|
|
327 options.no_split,
|
|
328 str_no_mismatches,
|
|
329 aligner_command,
|
|
330 db_path,
|
|
331 tmp_path,
|
|
332 outfile,
|
|
333 XS_pct,
|
|
334 XS_count,
|
|
335 options.adapter_mismatch,
|
|
336 options.Output_multiple_hit
|
|
337 )
|
|
338 else:
|
|
339 logm('Pair end')
|
|
340 # pair end specific default options
|
1
|
341 aligner_options = dict({BOWTIE: {'--fr' : True,
|
0
|
342 '-X' : options.max_insert_size,
|
1
|
343 '-I' : options.min_insert_size if options.min_insert_size > 0 else None,
|
|
344 '-a' : True # "-k 2" in bowtie would not report the best two
|
0
|
345 },
|
|
346 BOWTIE2 : {
|
1
|
347 '--fr' : True,
|
0
|
348 '-X' : options.max_insert_size,
|
|
349 '-I' : options.min_insert_size if options.min_insert_size > 0 else None,
|
|
350 '--no-discordant' : True,
|
1
|
351 '--no-mixed' : True,
|
|
352 '-k' : 2
|
0
|
353 },
|
|
354 SOAP: {
|
|
355 '-x' : options.max_insert_size,
|
|
356 '-m' : options.min_insert_size if options.min_insert_size > 0 else 100
|
|
357 }}[options.aligner],
|
|
358 # integrating 'rmappe' is different from others
|
|
359 **aligner_options)
|
|
360
|
|
361 aligner_command = aligner_exec + aligner_options_string() + \
|
|
362 { BOWTIE : ' %(reference_genome)s -f -1 %(input_file_1)s -2 %(input_file_2)s %(output_file)s',
|
|
363 BOWTIE2 : ' -x %(reference_genome)s -f -1 %(input_file_1)s -2 %(input_file_2)s -S %(output_file)s',
|
|
364 SOAP : ' -D %(reference_genome)s.fa.index -o %(output_file)s -a %(input_file_1)s -b %(input_file_2)s -2 %(output_file)s.unpaired' #,
|
|
365 # RMAP : # rmappe, also paste two inputs into one file.
|
|
366 }[options.aligner]
|
|
367
|
|
368 logm('Aligner command: %s' % aligner_command)
|
|
369
|
1
|
370 if '--end-to-end' not in aligner_options:
|
|
371 aligner_options_defaults[BOWTIE2].update({'-D' : 50})
|
|
372 else:
|
|
373 aligner_options_defaults[BOWTIE2].update({'-D' : 50, '-L': 15, '--score-min': 'L,-0.6,-0.6' })
|
|
374
|
0
|
375 bs_pair_end(options.infilename_1,
|
|
376 options.infilename_2,
|
|
377 asktag,
|
|
378 options.adapter_file,
|
|
379 options.cutnumber1,
|
|
380 options.cutnumber2,
|
|
381 options.no_split,
|
|
382 str_no_mismatches,
|
|
383 aligner_command,
|
|
384 db_path,
|
|
385 tmp_path,
|
|
386 outfile,
|
|
387 XS_pct,
|
|
388 XS_count,
|
1
|
389 options.adapter_mismatch,
|
0
|
390 options.Output_multiple_hit
|
|
391 )
|
|
392
|
|
393 outfile.close()
|
|
394
|