-
Notifications
You must be signed in to change notification settings - Fork 6
/
splitbam.py
executable file
·51 lines (40 loc) · 1.11 KB
/
splitbam.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
#!/usr/bin/env python
"""Split BAM file
"""
#--- standard library imports
#
import sys
import os
# --- third party imports
#
import pysam
#--- project specific imports
#
# /
__author__ = "Andreas Wilm"
__version__ = "0.1"
__email__ = "[email protected]"
__license__ = "WTFPL (http://www.wtfpl.net/)"
def main(bam_in, outprefix, splitevery=100000):
"""main function"""
bam_fh_in = pysam.Samfile(bam_in, "rb")
bam_fh_out = None
out_num = -1
for (n, r) in enumerate(bam_fh_in):
if n % splitevery == 0:
if bam_fh_out:
bam_fh_out.close()
out_num += 1
bam_fh_out = pysam.Samfile("%s%d.bam" % (outprefix, out_num),
"wb", template=bam_fh_in)
bam_fh_out.write(r)
bam_fh_in.close()
if __name__ == "__main__":
try:
bam_in = sys.argv[1]
outprefix = sys.argv[2]
splitevery = int(sys.argv[3])
except IndexError:
sys.stderr.write("Usage: %s in.bam outprefix splitevery\n" % os.path.basename(sys.argv[0]))
sys.exit(1)
main(bam_in, outprefix, splitevery)