-
Notifications
You must be signed in to change notification settings - Fork 0
/
make_bwa_jobs.py
executable file
·1035 lines (858 loc) · 35.8 KB
/
make_bwa_jobs.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
Create cluster job files to align a batch of reads to a genome, using bwa.
"""
from sys import argv,stdin,stdout,stderr,exit
from re import compile
from math import ceil
def usage(s=None):
message = """
usage: make_bwa_jobs [options]
--base=<path> path prefix; other filenames can use "{base}" to
refer to this path
--ref=<filename> (mandatory) name of reference fasta file
we also expect a bwa reference index in
<filename>.bwt, <filename>.pac, <filename>.ann,
<filename>.amb, and <filename>.sa
--reads=<filename> (mandatory,cumulative) name of query fastq file(s)
these must contain {mate} to indicate "1" or "2",
and may optionally contain a short identifier as a
prefix ending in ":"; e.g.
W1:reads/MQ854_K763WCJIIW_s_1_{mate}.fastq
--phred64to33 convert fastq files from phred+64 to phred+33 'on
the fly'
--readgroupinfo=<string> read group info string to shove into the sam header,
e.g. "ID:SRR748091 SM:SAMN01920490 PL:Illumina LB:lib1 PU:unknown"
(this is only supported for sampe)
--id=<string> unique identifier for this project
--job=<path> (mandatory) where to create job files
--results=<path> (mandatory) where to write alignment results
--subblocks=[<L>:]<filespec> create several jobs for each reads file, with
each job dealing with on "block" of the reads;
<filespec> is the name of a file suitable for use
with extract_blocks (a tabulated index); <L> is
the number of lines (in that index) to process in
each job; if there is more than one reads file,
<filespec> must contain "{reads}" which is
replaced by the reads file name; a typical
<filespec> is:
{reads}.tabulated
--exe:bwa=<filename> location of bwa executable
--aln=<params> (cumulative) parameters to pass to bwa aln
--sampe=<params> (cumulative) parameters to pass to bwa sampe
--mem[=<params>] (cumulative) parameters to pass to bwa mem
(by default we run "bwa aln" and "bwa sampe"
--mem:unpaired[=<params>] (cumulative) parameters to pass to bwa mem, and
we're aligning reads as unpaired
--sort=<params> (cumulative) parameters to pass to samtools sort
--memory:aln=<bytes> run-time memory limit for aln (e.g. "5.6G")
add ":ulimit" to enforce this in the shell script
--memory:sampe=<bytes> run-time memory limit for sampe (e.g. "5.6G")
add ":ulimit" to enforce this in the shell script
--memory:mem=<bytes> run-time memory limit for mem (e.g. "5.6G")
add ":ulimit" to enforce this in the shell script
--threads:aln=<number> number of threads for aln
--threads:sampe=<number> number of threads for sampe
--threads:mem=<number> number of threads for mem
--initialize=<text> (cumulative) shell command to add to job beginning
"shebang:bash" is mapped "#!/usr/bin/env bash"
other commands are copied "as is"
--nojobnames inhibit job names in submission list
--outputas=sam output in sam format (this is the default)
--outputas=bam output in bam format
--outputas=bamsorted output in sorted bam format
Typical command line:
make_bwa_jobs \\
--base=" /home/username/projects/orange" \\
--ref=" {base}/reference/MalusDomestica0.fa" \\
--id=" apple" \
--reads=" {id}1:reads/MQ854_K763WCJIIW_s_1_{mate}.fastq" \\
--job=" {base}/jobs" \\
--results="{base}/results" \\
--aln=" -I -q 15 -l 35 -k 2 -n 0.04 -o 2 -e 6" \\
--sampe=" -P -n 100 -N 100" \\
--memory:aln=" 5.6G" \\
--memory:sampe="6.2G" """
if (s == None): exit (message)
else: exit ("%s%s" % (s,message))
def main():
global basePath,refFilename,readsFilespecs,jobDirectory,resultsDirectory
global bwaProgramName,commandParams,phred64to33
global bashInitializers,maxMemory,numThreads,readGroupInfo
global jobId,giveJobsNames,jobNumber
global outputAs
global debug
# parse the command line
basePath = None
refFilename = None
readsFilespecs = None
phred64to33 = False
readGroupInfo = None
jobId = None
jobDirectory = None
resultsDirectory = None
subsampleFileSpec = None
subsampleBlockSize = None
bwaProgramName = None
aligner = "aln"
commandParams = {}
maxMemory = {}
numThreads = {}
bashInitializers = ["set -eu"]
giveJobsNames = True
outputAs = "sam"
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("--exe:bwa=")) or (arg.startswith("--bwaexe=")):
bwaProgramName = argVal
elif (arg.startswith("--reads=")):
if (readsFilespecs == None): readsFilespecs = []
readsFilespecs += argVal.split(",")
elif (arg == "--phred64to33"):
phred64to33 = True
elif (arg.startswith("--readgroupinfo=")):
readGroupInfo = "\\t".join(argVal.split())
elif (arg.startswith("--id=")):
jobId = argVal
elif (arg.startswith("--job=")):
jobDirectory = argVal
elif (arg.startswith("--results=")):
resultsDirectory = argVal
elif (arg.startswith("--subblocks=")):
# we allow --subblocks=spec or --subblocks=L:spec
subsampleFileSpec = subsampleBlockSize = None
if (":" not in argVal):
subsampleBlockSize = 1
subsampleFileSpec = argVal
else:
(subsampleBlockSize,subsampleFileSpec) = argVal.split(":",1)
subsampleBlockSize = int(subsampleBlockSize)
assert (subsampleBlockSize >= 1)
elif (arg.startswith("--aln=")) or (arg.startswith("--params:aln=")):
params = argVal
if ("aln" not in commandParams): commandParams["aln"] = []
commandParams["aln"] += [params]
elif (arg.startswith("--sampe=")) or (arg.startswith("--params:sampe=")):
params = argVal
if ("sampe" not in commandParams): commandParams["sampe"] = []
commandParams["sampe"] += [params]
elif (arg.startswith("--mem=")) or (arg.startswith("--params:mem=")):
params = argVal
if ("mem" not in commandParams): commandParams["mem"] = []
commandParams["mem"] += [params]
aligner = "mem"
elif (arg == "--mem"):
aligner = "mem"
elif (arg.startswith("--mem:unpaired=")) or (arg.startswith("--params:memunpaired=")):
params = argVal
if ("mem" not in commandParams): commandParams["mem"] = []
commandParams["mem"] += [params]
aligner = "mem unpaired"
elif (arg == "--mem:unpaired"):
aligner = "mem unpaired"
elif (arg.startswith("--sort=")) or (arg.startswith("--params:sort=")):
params = argVal
if ("sort" not in commandParams): commandParams["sort"] = []
commandParams["sort"] += [params]
elif (arg.startswith("--memory:aln=")):
if (argVal.endswith(":ulimit")):
argVal = argVal[:-len(":ulimit")]
maxMemory["aln"] = argVal
maxMemory["aln:ulimit"] = True
else:
maxMemory["aln"] = argVal
elif (arg.startswith("--memory:sampe=")):
if (argVal.endswith(":ulimit")):
argVal = argVal[:-len(":ulimit")]
maxMemory["sampe"] = argVal
maxMemory["sampe:ulimit"] = True
else:
maxMemory["sampe"] = argVal
elif (arg.startswith("--memory:mem=")):
if (argVal.endswith(":ulimit")):
argVal = argVal[:-len(":ulimit")]
maxMemory["mem"] = argVal
maxMemory["mem:ulimit"] = True
else:
maxMemory["mem"] = argVal
elif (arg.startswith("--threads:aln=")):
val = int(argVal)
assert (val > 0)
if (val > 1): numThreads["aln"] = val
elif (arg.startswith("--threads:sampe=")):
val = int(argVal)
assert (val > 0)
if (val > 1): numThreads["sampe"] = val
elif (arg.startswith("--threads:mem=")):
val = int(argVal)
assert (val > 0)
if (val > 1): numThreads["mem"] = val
elif (arg.startswith("--initialize=")) or (arg.startswith("--init=")):
if (argVal == "shebang:bash"):
argVal = "#!/usr/bin/env bash"
if (argVal == "set -eu"):
bashInitializers = [x for x in bashInitializers if (x != "set -eu")]
bashInitializers += [argVal]
elif (arg == "--nojobnames"):
giveJobsNames = False
elif (arg.startswith("--outputas=")) and (argVal == "sam"):
outputAs = "sam"
elif (arg.startswith("--outputas=")) and (argVal == "bam"):
outputAs = "bam"
elif (arg.startswith("--outputas=")) and (argVal in ["bamsorted","sortedbam"]):
outputAs = "sorted bam"
elif (arg == "--debug"):
debug += ["debug"]
elif (arg.startswith("--debug=")):
debug += argVal.split(",")
elif (arg.startswith("--")):
usage("unrecognized option: %s" % arg)
else:
usage("unrecognized option: %s" % arg)
# validate params
assert (refFilename != None)
assert (readsFilespecs != None)
assert (jobDirectory != None)
assert (resultsDirectory != None)
if (len(readsFilespecs) > 1) and (subsampleFileSpec != None):
assert ("{reads}" in subsampleFileSpec)
# perform filename substitution
if (basePath != None) and (basePath.endswith("/")):
basePath = basePath[:-1]
refFilename = do_filename_substitutition(refFilename)
for (ix,filename) in enumerate(readsFilespecs):
readsFilespecs[ix] = do_filename_substitutition(filename)
if (aligner != "mem unpaired"):
assert ("{mate}" in readsFilespecs[ix])
if (subsampleFileSpec != None):
subsampleFileSpec = do_filename_substitutition(subsampleFileSpec)
jobDirectory = do_filename_substitutition(jobDirectory)
if (jobDirectory.endswith("/")):
jobDirectory = jobDirectory[:-1]
resultsDirectory = do_filename_substitutition(resultsDirectory)
if (resultsDirectory.endswith("/")):
resultsDirectory = resultsDirectory[:-1]
if (bwaProgramName == None):
bwaProgramName = "bwa"
else:
bwaProgramName = do_filename_substitutition(bwaProgramName)
for command in commandParams:
for (ix,param) in enumerate(commandParams[command]):
commandParams[command][ix] = do_filename_substitutition(param)
for (ix,bashInitializer) in enumerate(bashInitializers):
bashInitializer = do_filename_substitutition(bashInitializer)
bashInitializers[ix] = bashInitializer
if (aligner == "aln"):
assert ("mem" not in commandParams)
assert ("mem" not in maxMemory)
assert ("mem" not in numThreads)
elif (aligner == "mem"):
assert ("aln" not in commandParams)
assert ("aln" not in maxMemory)
assert ("aln" not in numThreads)
assert ("sampe" not in commandParams)
assert ("sampe" not in maxMemory)
assert ("sampe" not in numThreads)
elif (aligner == "mem unpaired"):
assert ("aln" not in commandParams)
assert ("aln" not in maxMemory)
assert ("aln" not in numThreads)
assert ("sampe" not in commandParams)
assert ("sampe" not in maxMemory)
assert ("sampe" not in numThreads)
if (phred64to33):
assert (aligner in ["mem","mem unpaired"])
# convert memory specifications
if ("aln:ulimit" in maxMemory):
multiplier = 1
val = maxMemory["aln"]
if (val.startswith("{threads}*")):
if ("aln" in numThreads): multiplier = numThreads["aln"]
val = val.replace("{threads}*","")
elif (val.endswith("*{threads}")):
if ("aln" in numThreads): multiplier = numThreads["aln"]
val = val.replace("*{threads}","")
maxMemory["aln"] = int_with_unit(val) * multiplier
elif ("aln" in maxMemory):
val = maxMemory["aln"]
maxMemory["aln"] = int_with_unit(val)
if ("sampe:ulimit" in maxMemory):
multiplier = 1
val = maxMemory["sampe"]
if (val.startswith("{threads}*")):
if ("sampe" in numThreads): multiplier = numThreads["sampe"]
val = val.replace("{threads}*","")
elif (val.endswith("*{threads}")):
if ("sampe" in numThreads): multiplier = numThreads["sampe"]
val = val.replace("*{threads}","")
maxMemory["sampe"] = int_with_unit(val) * multiplier
elif ("sampe" in maxMemory):
val = maxMemory["sampe"]
maxMemory["sampe"] = int_with_unit(val)
if ("mem:ulimit" in maxMemory):
multiplier = 1
val = maxMemory["mem"]
if (val.startswith("{threads}*")):
if ("mem" in numThreads): multiplier = numThreads["mem"]
val = val.replace("{threads}*","")
elif (val.endswith("*{threads}")):
if ("mem" in numThreads): multiplier = numThreads["mem"]
val = val.replace("*{threads}","")
maxMemory["mem"] = int_with_unit(val) * multiplier
elif ("mem" in maxMemory):
val = maxMemory["mem"]
maxMemory["mem"] = int_with_unit(val)
# read the sub-block tabulation files, to determine their lengths
if ("subblocks" in debug):
print >>stderr, "subsampleFileSpec = %s" % subsampleFileSpec
print >>stderr, "subsampleBlockSize = %d" % subsampleBlockSize
readsToTabulation = None
if (subsampleFileSpec == None):
subsampleN = None
else:
readsToTabulation = {}
subsampleN = {}
subsampleW = 1
for readsFilespec in readsFilespecs:
# nota bene: we assume the tabulation files for both mates have the
# same number of lines
(_,_,readsMatespec) = interpret_filespec(readsFilespec,replaceMate=False)
subsampleFilename = subsampleFileSpec.replace("{reads}",readsMatespec)
subsampleFilename = subsampleFilename.replace("{mate}", "1")
numLines = number_of_lines_in(subsampleFilename)
readsToTabulation[readsFilespec] = subsampleFilename
subLinesList = []
for startLine in xrange(0,numLines,subsampleBlockSize):
endLine = min(startLine+subsampleBlockSize,numLines)
subLinesList += ["%d..%d" % (startLine+1,endLine)]
subsampleN[readsFilespec] = subLinesList
subsampleW = max(subsampleW,len(str(len(subLinesList))))
if ("subblocks" in debug):
print >>stderr, "subsampleN[%s] = #%d [%s]" \
% (readsFilespec,len(subLinesList),",".join(subLinesList))
# write the jobs
jobs = []
jobNumber = -1
if (aligner == "aln"):
for jobSpec in job_specs(readsFilespecs,mateSet=[1,2,"P"],subsampleN=subsampleN):
jobNumber += 1
(readsFilespec,mate,subK,subLines) = jobSpec
if (subK != None): subK = "%0*d" % (subsampleW,subK)
if (mate == 1): dependencies = [jobNumber]
elif (mate != "P"): dependencies += [jobNumber]
if (type(mate) == int):
jobInfo = create_aln_job(readsFilespec,mate,subK,subLines)
elif (mate == "P"):
jobInfo = create_sampe_job(readsFilespec,subK,subLines,dependencies)
else:
assert (False), "Internal Error: mate = \"%s\"" % mate
jobs += [jobInfo]
elif (aligner == "mem"):
for jobSpec in job_specs(readsFilespecs,mateSet=["P"],subsampleN=subsampleN):
jobNumber += 1
(readsFilespec,mate,subK,subLines) = jobSpec
if (subK != None): subK = "%0*d" % (subsampleW,subK)
jobInfo = create_mem_job(readsFilespec,subK,subLines)
jobs += [jobInfo]
elif (aligner == "mem unpaired"):
for jobSpec in job_specs(readsFilespecs,mateSet=[None],subsampleN=subsampleN):
jobNumber += 1
(readsFilespec,mate,subK,subLines) = jobSpec
if (subK != None): subK = "%0*d" % (subsampleW,subK)
jobInfo = create_mem_unpaired_job(readsFilespec,subK,subLines)
jobs += [jobInfo]
# print the jobs list file
fn = [jobDirectory,"/"]
if (jobId != None): fn += [jobId]
fn += [".bwa_map"]
fn += [".job_list"]
fn += [".txt"]
fn = "".join(fn)
print >>stderr, "writing \"%s\"" % fn
f = file(fn, "wt")
print >>f, "\n".join(jobs)
f.close()
# create a "bwa aln" job
def create_aln_job(readsFilespec,mate,subK,subLines):
(dataset,readsId,_) = interpret_filespec(readsFilespec)
readsFilename = do_reads_filename_substitutition(readsFilespec,mate)
# determine job name
jobName = []
if (jobId != None): jobName += [jobId]
jobName += [dataset]
if (subK != None): jobName += [subK]
jobName += [str(mate)]
jobName = ".".join(jobName)
resultsFilename = resultsDirectory + "/" + jobName + ".sai"
if (giveJobsNames):
shortJobName = []
if (readsId != None): shortJobName += [readsId]
else: shortJobName += [str(jobNumber)]
if (subK != None): shortJobName += [subK]
shortJobName += [str(mate)]
shortJobName = "_".join(shortJobName)
# create the job file, and the entry for the jobs list
fn = jobDirectory + "/" + jobName + ".sh"
print >>stderr, "writing \"%s\"" % fn
jobF = file(fn,"wt")
jobInfo = []
if (giveJobsNames): jobInfo += ["%d %s %s" % (jobNumber,shortJobName,fn)]
else: jobInfo += ["%d %s" % (jobNumber,fn)]
if ("aln" in maxMemory): jobInfo += ["--memory=%d" % int(ceil(maxMemory["aln"]/1000000000.0))]
if ("aln" in numThreads): jobInfo += ["--cores=%d" % numThreads["aln"]]
# write the job file
if (bashInitializers == None): myBashInitializers = []
else: myBashInitializers = [x for x in bashInitializers]
if ("aln" in maxMemory):
memPages = int(ceil(maxMemory["aln"]/1024.0))
myBashInitializers += ["ulimit -v %d # %s bytes" \
% (memPages,commatize(memPages*1024))]
if (myBashInitializers != []):
print >>jobF, "\n".join(myBashInitializers)
print >>jobF
pipe = []
if (subLines != None):
command = ["extract_block"]
command += ["--block=%s.tabulated:%s" % (readsFilename,subLines)]
command += ["--path=%s" % readsFilename]
pipe += [" \\\n ".join(command)]
command = ["%s aln " % bwaProgramName]
if ("aln" in commandParams): command += [" ".join(commandParams["aln"])]
if ("aln" in numThreads): command += ["-t %d" % numThreads["aln"]]
command += [refFilename]
if (pipe == []): command += [readsFilename]
else: command += ["/dev/stdin"]
if (pipe == []): pipe += [" \\\n ".join(command)]
else: pipe += [" | %s" % "\\\n ".join(command)]
pipe += [" > %s" % resultsFilename]
print >>jobF, "time " + " \\\n".join(pipe)
jobF.close()
return " ".join(jobInfo)
# create a "bwa sampe" job
def create_sampe_job(readsFilespec,subK,subLines,dependencies):
(dataset,readsId,_) = interpret_filespec(readsFilespec)
readsFilename1 = do_reads_filename_substitutition(readsFilespec,1)
readsFilename2 = do_reads_filename_substitutition(readsFilespec,2)
if (dependencies == []): dependencies = None
# determine job name
jobName = []
if (jobId != None): jobName += [jobId]
jobName += [dataset]
if (subK != None): jobName += [subK]
jobName += ["{mate}"]
jobName = ".".join(jobName)
if (outputAs == "bam"): resultsExt = ".bam"
elif (outputAs == "sorted bam"): resultsExt = "" # (samtools will add ".bam")
else: resultsExt = ".sam"
resultsFilename1 = resultsDirectory + "/" + jobName.replace(".{mate}",".1") + ".sai"
resultsFilename2 = resultsDirectory + "/" + jobName.replace(".{mate}",".2") + ".sai"
resultsFilename = resultsDirectory + "/" + jobName.replace(".{mate}","") + resultsExt
jobName = jobName.replace(".{mate}",".P")
if (giveJobsNames):
shortJobName = []
if (readsId != None): shortJobName += [readsId]
else: shortJobName += [str(jobNumber)]
if (subK != None): shortJobName += [subK]
shortJobName += ["P"]
shortJobName = "_".join(shortJobName)
# create the job file, and the entry for the jobs list
fn = jobDirectory + "/" + jobName + ".sh"
print >>stderr, "writing \"%s\"" % fn
jobF = file(fn,"wt")
jobInfo = []
if (giveJobsNames): jobInfo += ["%d %s %s" % (jobNumber,shortJobName,fn)]
else: jobInfo += ["%d %s" % (jobNumber,fn)]
if (dependencies != None): jobInfo += ["--depend=%s" % ",".join([str(x) for x in dependencies])]
if ("sampe" in maxMemory): jobInfo += ["--memory=%d" % int(ceil(maxMemory["sampe"]/1000000000.0))]
if ("sampe" in numThreads): jobInfo += ["--cores=%d" % numThreads["sampe"]]
# write the job file
if (bashInitializers == None): myBashInitializers = []
else: myBashInitializers = [x for x in bashInitializers]
if ("sampe" in maxMemory):
memPages = int(ceil(maxMemory["sampe"]/1024.0))
myBashInitializers += ["ulimit -v %d # %s bytes" \
% (memPages,commatize(memPages*1024))]
if (myBashInitializers != []):
print >>jobF, "\n".join(myBashInitializers)
print >>jobF
pipe = []
command = ["%s sampe" % bwaProgramName]
if ("sampe" in commandParams): command += [" ".join(commandParams["sampe"])]
if (readGroupInfo != None): command += ["-r \"@RG\\t%s\"" % readGroupInfo]
if ("sampe" in numThreads): command += ["-t %d" % numThreads["sampe"]]
command += [refFilename]
command += [resultsFilename1]
command += [resultsFilename2]
if (subLines == None):
command += [readsFilename1]
command += [readsFilename2]
else:
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename1,subLines)]
command += [" --path=%s)" % readsFilename1]
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename2,subLines)]
command += [" --path=%s)" % readsFilename2]
pipe += [" \\\n ".join(command)]
if (outputAs == "bam"):
pipe += [" | samtools view -Sb /dev/stdin"]
pipe += [" > %s" % resultsFilename]
elif (outputAs == "sorted bam"):
pipe += [" | samtools view -Su -"]
sortParams = ""
if ("sort" in commandParams):
jobIdForSort = jobId
if (subK != None): jobIdForSort += "." + subK
sortParams = " ".join(commandParams["sort"])
sortParams = sortParams.replace("{base}",basePath)
sortParams = sortParams.replace("{id}",jobIdForSort)
pipe += [" | samtools sort %s - -o %s.bam" % (sortParams,resultsFilename)]
else:
pipe += [" > %s" % resultsFilename]
print >>jobF, "time " + " \\\n".join(pipe)
jobF.close()
return " ".join(jobInfo)
# create a "bwa mem" job
def create_mem_job(readsFilespec,subK,subLines):
(dataset,readsId,_) = interpret_filespec(readsFilespec)
readsFilename1 = do_reads_filename_substitutition(readsFilespec,1)
readsFilename2 = do_reads_filename_substitutition(readsFilespec,2)
# determine job name
jobName = []
if (jobId != None): jobName += [jobId]
jobName += [dataset]
if (subK != None): jobName += [subK]
jobName += ["{mate}"]
jobName = ".".join(jobName)
if (outputAs == "bam"): resultsExt = ".bam"
elif (outputAs == "sorted bam"): resultsExt = "" # (samtools will add ".bam")
else: resultsExt = ".sam"
resultsFilename = resultsDirectory + "/" + jobName.replace(".{mate}","") + resultsExt
jobName = jobName.replace(".{mate}",".P")
if (giveJobsNames):
shortJobName = []
if (readsId != None): shortJobName += [readsId]
else: shortJobName += [str(jobNumber)]
if (subK != None): shortJobName += [subK]
shortJobName += ["P"]
shortJobName = "_".join(shortJobName)
# create the job file, and the entry for the jobs list
fn = jobDirectory + "/" + jobName + ".sh"
print >>stderr, "writing \"%s\"" % fn
jobF = file(fn,"wt")
jobInfo = []
if (giveJobsNames): jobInfo += ["%d %s %s" % (jobNumber,shortJobName,fn)]
else: jobInfo += ["%d %s" % (jobNumber,fn)]
if ("mem" in maxMemory): jobInfo += ["--memory=%d" % int(ceil(maxMemory["mem"]/1000000000.0))]
if ("mem" in numThreads): jobInfo += ["--cores=%d" % numThreads["mem"]]
# write the job file
if (bashInitializers == None): myBashInitializers = []
else: myBashInitializers = [x for x in bashInitializers]
if ("mem" in maxMemory):
memPages = int(ceil(maxMemory["mem"]/1024.0))
myBashInitializers += ["ulimit -v %d # %s bytes" \
% (memPages,commatize(memPages*1024))]
if (myBashInitializers != []):
print >>jobF, "\n".join(myBashInitializers)
print >>jobF
mustUnzip = (readsFilename1.endswith(".gz") or readsFilename1.endswith(".gzip"))
pipe = []
command = ["%s mem" % bwaProgramName]
if ("mem" in commandParams): command += [" ".join(commandParams["mem"])]
if ("mem" in numThreads): command += ["-t %d" % numThreads["mem"]]
command += [refFilename]
if (subLines == None) and (not phred64to33) and (not mustUnzip):
command += [readsFilename1]
command += [readsFilename2]
elif (subLines == None) and (phred64to33) and (not mustUnzip):
command += ["<(cat %s" % readsFilename1]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
command += ["<(cat %s" % readsFilename2]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
if (subLines == None) and (not phred64to33) and (mustUnzip):
command += ["<(gzip -dc %s)" % readsFilename1]
command += ["<(gzip -dc %s)" % readsFilename2]
elif (subLines == None) and (phred64to33) and (mustUnzip):
command += ["<(gzip -dc %s" % readsFilename1]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
command += ["<(gzip -dc %s" % readsFilename2]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
elif (subLines != None) and (not phred64to33) and (not mustUnzip):
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename1,subLines)]
command += [" --path=%s)" % readsFilename1]
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename2,subLines)]
command += [" --path=%s)" % readsFilename2]
elif (subLines != None) and (phred64to33) and (not mustUnzip):
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename1,subLines)]
command += [" --path=%s" % readsFilename1]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename2,subLines)]
command += [" --path=%s" % readsFilename2]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
elif (subLines != None) and (not phred64to33) and (mustUnzip):
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename1,subLines)]
command += [" --path=%s" % readsFilename1]
command += [" | gzip -dc)"]
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename2,subLines)]
command += [" --path=%s" % readsFilename2]
command += [" | gzip -dc)"]
elif (subLines != None) and (phred64to33) and (mustUnzip):
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename1,subLines)]
command += [" --path=%s" % readsFilename1]
command += [" | gzip -dc"]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename2,subLines)]
command += [" --path=%s" % readsFilename2]
command += [" | gzip -dc"]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
pipe += [" \\\n ".join(command)]
if (outputAs == "bam"):
pipe += [" | samtools view -Sb /dev/stdin"]
pipe += [" > %s" % resultsFilename]
elif (outputAs == "sorted bam"):
pipe += [" | samtools view -Su -"]
sortParams = ""
if ("sort" in commandParams):
jobIdForSort = jobId
if (subK != None): jobIdForSort += "." + subK
sortParams = " ".join(commandParams["sort"])
sortParams = sortParams.replace("{base}",basePath)
sortParams = sortParams.replace("{id}",jobIdForSort)
pipe += [" | samtools sort %s - -o %s.bam" % (sortParams,resultsFilename)]
else:
pipe += [" > %s" % resultsFilename]
print >>jobF, "time " + " \\\n".join(pipe)
jobF.close()
return " ".join(jobInfo)
# create a "bwa mem" job for unpaired reads
def create_mem_unpaired_job(readsFilespec,subK,subLines):
(dataset,readsId,_) = interpret_filespec(readsFilespec,replaceMate=False)
readsFilename = do_reads_filename_substitutition(readsFilespec,None)
# determine job name
jobName = []
if (jobId != None): jobName += [jobId]
jobName += [dataset]
if (subK != None): jobName += [subK]
jobName = ".".join(jobName)
if (outputAs == "bam"): resultsExt = ".bam"
elif (outputAs == "sorted bam"): resultsExt = "" # (samtools will add ".bam")
else: resultsExt = ".sam"
resultsFilename = resultsDirectory + "/" + jobName + resultsExt
if (giveJobsNames):
shortJobName = []
if (readsId != None): shortJobName += [readsId]
else: shortJobName += [str(jobNumber)]
if (subK != None): shortJobName += [subK]
shortJobName = "_".join(shortJobName)
# create the job file, and the entry for the jobs list
fn = jobDirectory + "/" + jobName + ".sh"
print >>stderr, "writing \"%s\"" % fn
jobF = file(fn,"wt")
jobInfo = []
if (giveJobsNames): jobInfo += ["%d %s %s" % (jobNumber,shortJobName,fn)]
else: jobInfo += ["%d %s" % (jobNumber,fn)]
if ("mem" in maxMemory): jobInfo += ["--memory=%d" % int(ceil(maxMemory["mem"]/1000000000.0))]
if ("mem" in numThreads): jobInfo += ["--cores=%d" % numThreads["mem"]]
# write the job file
if (bashInitializers == None): myBashInitializers = []
else: myBashInitializers = [x for x in bashInitializers]
if ("mem" in maxMemory):
memPages = int(ceil(maxMemory["mem"]/1024.0))
myBashInitializers += ["ulimit -v %d # %s bytes" \
% (memPages,commatize(memPages*1024))]
if (myBashInitializers != []):
print >>jobF, "\n".join(myBashInitializers)
print >>jobF
mustUnzip = (readsFilename.endswith(".gz") or readsFilename.endswith(".gzip"))
pipe = []
command = ["%s mem" % bwaProgramName]
if ("mem" in commandParams): command += [" ".join(commandParams["mem"])]
if ("mem" in numThreads): command += ["-t %d" % numThreads["mem"]]
command += [refFilename]
if (subLines == None) and (not phred64to33) and (not mustUnzip):
command += [readsFilename]
elif (subLines == None) and (phred64to33) and (not mustUnzip):
command += ["<(cat %s" % readsFilename]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
if (subLines == None) and (not phred64to33) and (mustUnzip):
command += ["<(gzip -dc %s)" % readsFilename]
elif (subLines == None) and (phred64to33) and (mustUnzip):
command += ["<(gzip -dc %s" % readsFilename]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
elif (subLines != None) and (not phred64to33) and (not mustUnzip):
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename,subLines)]
command += [" --path=%s)" % readsFilename]
elif (subLines != None) and (phred64to33) and (not mustUnzip):
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename,subLines)]
command += [" --path=%s" % readsFilename]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
elif (subLines != None) and (not phred64to33) and (mustUnzip):
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename,subLines)]
command += [" --path=%s" % readsFilename]
command += [" | gzip -dc)"]
elif (subLines != None) and (phred64to33) and (mustUnzip):
command += ["<(extract_block"]
command += [" --block=%s.tabulated:%s" % (readsFilename,subLines)]
command += [" --path=%s" % readsFilename]
command += [" | gzip -dc"]
command += [" | fastq_convert_phred --from=phred+64 --to=phred+33)"]
pipe += [" \\\n ".join(command)]
if (outputAs == "bam"):
pipe += [" | samtools view -Sb /dev/stdin"]
pipe += [" > %s" % resultsFilename]
elif (outputAs == "sorted bam"):
pipe += [" | samtools view -Su -"]
sortParams = ""
if ("sort" in commandParams):
jobIdForSort = jobId
if (subK != None): jobIdForSort += "." + subK
sortParams = " ".join(commandParams["sort"])
sortParams = sortParams.replace("{base}",basePath)
sortParams = sortParams.replace("{id}",jobIdForSort)
pipe += [" | samtools sort %s - -o %s.bam" % (sortParams,resultsFilename)]
else:
pipe += [" > %s" % resultsFilename]
print >>jobF, "time " + " \\\n".join(pipe)
jobF.close()
return " ".join(jobInfo)
# perform filename substitutions
def do_filename_substitutition(s):
if ("{base}" in s):
assert (basePath != None)
s = s.replace("{base}",basePath)
return s
def do_reads_filename_substitutition(filespec,mate):
if (":" in filespec):
saveFilespec = filespec
numFields = len(filespec.split(":"))
assert (numFields == 2)
filespec = filespec.split(":",1)[1]
if (filespec == ""): filespec = saveFilespec
if (mate != None):
assert ("{mate}" in filespec)
filespec = filespec.replace("{mate}",str(mate))
return filespec
# extract info from a reads filespec
fileSpecRe = compile("(?P<mate>_*\{mate\}_*)")
def interpret_filespec(filespec,replaceMate=True):
readsId = None
if (":" in filespec):
saveFilespec = filespec
numFields = len(filespec.split(":"))
assert (numFields == 2)
(readsId,filespec) = filespec.split(":",1)
if (readsId == ""): readsId = None
if (filespec == ""): (readsId,filespec) = (None,saveFilespec)
if (readsId != None):
if (jobId != None): readsId = readsId.replace("{id}",jobId)
saveFilespec = filespec
if ("/" in filespec):
filespec = filespec.split("/")[-1]
if (filespec.endswith(".fastq")):
filespec = filespec[:filespec.rfind(".fastq")]
elif (filespec.endswith(".fq")):
filespec = filespec[:filespec.rfind(".fq")]
dataset = filespec
if (replaceMate):
m = fileSpecRe.search(filespec) # find first match
assert (m != None)
(sIx,eIx) = (m.start(),m.end())
m = fileSpecRe.search(filespec[eIx:]) # make sure there's no other match
assert (m == None)
replacement = ""
if (sIx != 0) and (eIx != len(filespec)): replacement = "_"
dataset = filespec[:sIx] + replacement + filespec[eIx:]
while (dataset[-1] in [".","_"]):
dataset = dataset[:-1]
return (dataset,readsId,saveFilespec)
# generate job specs, tuples of the format (filespec,mate,subsample,subInfo)
def job_specs(readsFilespecs,mateSet=2,subsampleN=None):
if (type(mateSet) == int):
assert (mateSet > 0)
else:
assert (mateSet != [])
if (subsampleN != None):
assert (type(subsampleN) == dict)
if (type(mateSet) != int):
for readFilespec in readsFilespecs:
if (subsampleN == None):
for mate in mateSet:
yield (readFilespec,mate,None,None)
else:
for (subK,subLines) in enumerate(subsampleN[readFilespec]):
for mate in mateSet:
yield (readFilespec,mate,subK+1,subLines)
elif (mateSet == 1):
for readFilespec in readsFilespecs:
if (subsampleN == None):
yield (readFilespec,None,None,None)
else:
for (subK,subLines) in enumerate(subsampleN[readFilespec]):
yield (readFilespec,None,subK+1,subLines)
else:
for readFilespec in readsFilespecs:
if (subsampleN == None):
for mate in xrange(1,mateSet+1):
yield (readFilespec,mate,None,None)
else:
for (subK,subLines) in enumerate(subsampleN[readFilespec]):
for mate in xrange(1,mateSet+1):
yield (readFilespec,mate,subK+1,subLines)
# number_of_lines_in--
# Count the number of lines in a file.
def number_of_lines_in(filename):
f = file(filename,"rt")
numLines = 0
for line in f:
numLines += 1
f.close()
return numLines
# int_with_unit--
# Parse a strings as an integer, allowing unit suffixes
def int_with_unit(s):
if (s.endswith("K")):
multiplier = 1000
s = s[:-1]
elif (s.endswith("M")):