-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_script_map.py
executable file
·279 lines (220 loc) · 8.05 KB
/
create_script_map.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python
"""
Create a cluster job file to map reads.
"""
from sys import argv,stdin,stdout,stderr,exit
def usage(s=None):
message = """
usage: create_script_map [options] > map.sh
<sub>_<samp>_<type> (required) run descriptor; for example, CS_NORM_PE
means subject "CS", sample "NORM", and type "PE";
other filenames can use "{run}" to refer to this
string
--base=<path> path prefix; other filenames can use "{base}" to
refer to this path
--ref=<filename> (required) bwa reference file
--reads=<filename> (required) fastq file(s); usually this looks like
this:
{base}/reads/{run}.{mate}.fastq
--bam=<filename> (required) place to write bam file(s); usually
this looks like this:
{base}/alignments/{run}
--namesorted create a name sorted bam file too
--qualityfiltered create a quality filtered bam file too
--temp=<filename> path to place to store temporary files
(default is {base}/temp/{run}.temp)
--initialize=<text> (cumulative) shell command to add to job beginning
"shebang:bash" is mapped "#!/usr/bin/env bash"
other commands are copied "as is" """
if (s == None): exit (message)
else: exit ("%s%s" % (s,message))
def main():
global basePath,runName
global debug
bashShebang = "#!/usr/bin/env bash"
# parse args
runName = None
basePath = None
refFilename = None
readsFilename = None
bamFilename = None
tempFilename = None
doNameSorted = False
doQualityFiltering = False
bashInitializers = ["set -eu"]
debug = []
for arg in argv[1:]:
if ("=" in arg):
argVal = arg.split("=",1)[1].strip()
if (arg.startswith("--base=")) or (arg.startswith("--basepath=")) or (arg.startswith("--path=")):
basePath = argVal
elif (arg.startswith("--reference=")) or (arg.startswith("--ref=")):
refFilename = argVal
elif (arg.startswith("--reads=")):
readsFilename = argVal
elif (arg.startswith("--bam=")):
bamFilename = argVal
elif (arg == "--namesorted"):
doNameSorted = True
elif (arg == "--qualityfiltered"):
doQualityFiltering = True
elif (arg.startswith("--temp=")):
tempFilename = argVal
elif (arg.startswith("--initialize=")) or (arg.startswith("--init=")):
if (argVal == "shebang:bash"):
argVal = bashShebang
if (argVal == "set -eu"):
bashInitializers = [x for x in bashInitializers if (x != "set -eu")]
bashInitializers += [argVal]
elif (arg == "--debug"):
debug += ["debug"]
elif (arg.startswith("--debug=")):
debug += argVal.split(",")
elif (arg.startswith("--")):
usage("unrecognized option: %s" % arg)
elif (runName == None):
fields = arg.split(":",2)
if (len(fields) != 3):
fields = arg.split("_")
if (len(fields) < 3) or (fields[-1] not in ["PE","MP"]):
usage("\"%s\" is not a valid run descriptor" % arg)
runName = "_".join(fields)
else:
usage("unrecognized option: %s" % arg)
if (runName == None):
usage("you have to give me a run descriptor")
if (refFilename == None):
usage("you have to give me a bwa sequence reference")
if (bamFilename == None):
usage("you have to give me a bam filename")
if (tempFilename == None):
tempFilename = "{base}/temp/{run}.temp"
##########
# perform filename substitution
##########
if (basePath == None): basePath = "."
elif (basePath.endswith("/")): basePath = basePath[:-1]
refFilename = do_filename_substitutition(refFilename)
readsFilename = do_filename_substitutition(readsFilename)
bamFilename = do_filename_substitutition(bamFilename)
tempFilename = do_filename_substitutition(tempFilename)
if (bamFilename.endswith(".bam")): bamFilename = bamFilename[:-4]
##########
# create the job's shell script
##########
# write bash intitializers
if (bashInitializers != None):
for (ix,bashInitializer) in enumerate(bashInitializers):
if (bashInitializer != bashShebang): continue
print bashInitializer
bashInitializers[ix] = None
for (ix,bashInitializer) in enumerate(bashInitializers):
if (bashInitializer != "set -eu"): continue
print bashInitializer
bashInitializers[ix] = None
for bashInitializer in bashInitializers:
if (bashInitializer == None): continue
print do_filename_substitutition(bashInitializer)
print
# write commands describing the files the script will create
print "echo \"will write alignments to %s\"" % (bamFilename + ".bam")
if (doNameSorted):
print "echo \"will write name-sorted alignments to %s\"" % (bamFilename + ".name_sorted.bam")
if (doQualityFiltering):
qfBamInFilename = bamFilename + ".bam"
qfBamOutFilename = "%s.ql_filtered.bam" % bamFilename
if (doNameSorted):
qfBamInFilename = "%s.name_sorted.bam" % bamFilename
qfBamOutFilename = "%s.ql_filtered.name_sorted.bam" % bamFilename
print "echo \"will write quality-filtered alignments to %s\"" % qfBamOutFilename
# write command(s) to map the reads
commands = []
command = ["time bwa mem"]
command += [refFilename]
command += [readsFilename.replace("{mate}","1")]
command += [readsFilename.replace("{mate}","2")]
commands += [command]
command = ["> " + tempFilename + ".sam"]
commands += [command]
print
print "echo \"=== mapping reads ===\""
print
print commands_to_pipeline(commands)
# write command(s) to position-sort the alignments and convert to bam
commands = []
command = ["time samtools sort"]
command += ["-T %s" % tempFilename]
command += ["-o %s.bam" % bamFilename]
command += [tempFilename + ".sam"]
commands += [command]
print
print "echo \"=== position-sorting alignments ===\""
print
print commands_to_pipeline(commands)
# write command(s) to name-sort the alignments
if (doNameSorted):
commands = []
command = ["time samtools sort -n"]
command += ["-T %s" % tempFilename]
command += ["-o %s.name_sorted.bam" % bamFilename]
command += [bamFilename + ".bam"]
commands += [command]
print
print "echo \"=== name-sorting alignments ===\""
print
print commands_to_pipeline(commands)
# write command(s) to quality-filter the alignments
if (doQualityFiltering):
commands = []
command = ["time samtools view -h %s" % qfBamInFilename]
commands += [command]
command = ["filtered_sam_to_intervals"]
if (doNameSorted): command += ["--namesorted"]
command += ["--prohibit:\"(CIGAR == *)\""]
command += ["--require:\" (RNEXT == =)\""]
command += ["--require:\" (MAPCLIP >= RLEN*${clipThreshold})\""]
command += ["--require:\" (MINCLIP <= 5)\""]
command += ["--require:\" (MAPQ >= ${mapQThreshold})\""]
command += ["--justsam"]
command += ["--progress=2M --progress=output:2M"]
commands += [command]
command = ["samtools view -bS -"]
commands += [command]
command = ["> %s" % qfBamOutFilename]
commands += [command]
print
print "echo \"=== quality-filtering alignments ===\""
print
print "mapQThreshold=40"
print "clipThreshold=0.40"
print commands_to_pipeline(commands)
# write command(s) to clean up
commands = []
command = ["rm " + tempFilename + ".sam"]
commands += [command]
print
print "echo \"=== cleaning up ===\""
print
print commands_to_pipeline(commands)
def commands_to_pipeline(commands):
pipeline = []
for (cmdNum,cmd) in enumerate(commands):
if (cmdNum == 0): prefix = ""
else: prefix = " | "
if (cmd[0].startswith(">")):
assert (cmdNum != 0)
assert (len(cmd) == 1)
prefix = " "
pipeline += [prefix + cmd[0]]
for line in cmd[1:]:
pipeline += [" " + line]
return " \\\n".join(pipeline)
def do_filename_substitutition(s):
if ("{base}" in s):
assert (basePath != None)
s = s.replace("{base}",basePath)
if ("{run}" in s):
assert (runName != None)
s = s.replace("{run}",runName)
return s
if __name__ == "__main__": main()