forked from brianpenghe/bamsam-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerateBAMheader.py
55 lines (45 loc) · 1.39 KB
/
generateBAMheader.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
##################################
# #
# Last modified 04/26/2012 #
# #
# Georgi Marinov #
# #
##################################
import sys
import pysam
import string
def main(argv):
if len(argv) < 3:
print 'usage: python %s BAM chrom.sizes outfilename' % argv[0]
sys.exit(1)
BAM = argv[1]
chromsizes = argv[2]
outputfilename = argv[3]
ChrDict={}
linelist = open(chromsizes)
for line in linelist:
fields = line.strip().split('\t')
chr = fields[0]
size = fields[1]
ChrDict[chr]=size
outfile = open(outputfilename, "w")
outline = '@HD\tVN:1.0\tSO:sorted'
outfile.write(outline+'\n')
SeenDict={}
i=0
samfile = pysam.Samfile(BAM, "rb" )
for alignedread in samfile.fetch():
i+=1
if i % 5000000 == 0:
print 'examining read multiplicity', str(i/1000000) + 'M alignments processed processed', chr, alignedread.pos, ChrDict[chr]
chr = samfile.getrname(alignedread.tid)
if SeenDict.has_key(chr):
continue
else:
outline = '@SQ\tSN:' + chr + '\tLN:' + ChrDict[chr]
print outline
outfile.write(outline+'\n')
SeenDict[chr]=''
outfile.close()
if __name__ == '__main__':
main(sys.argv)