-
Notifications
You must be signed in to change notification settings - Fork 0
/
coverage_counter.py
193 lines (152 loc) · 6.4 KB
/
coverage_counter.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
""" position_coverage_counter
Usage: python position_coverage_counter.py -c chromosome -i accepted_hit.bam -t threshold -o outputPrefix
Input: -c chromosome name, -i bam file with mapped reads, -o the directory and prefix of output files
Output: the header line is the chromosome name and size, follow by lines with {position \t readcount \n}
note: the ouput only report the position with non-zero count
Function: 1. convert the bam file to sam file
2. traverse the sam file and select the mapping for a specific chromosome
3. ignore the mapping whose quality falls below a certain threshold
4. include multiple mapping (ie count all the positions the read maps to)
5. note: this program also handles pair-end reads
Date: 2013-12-26
Author: Chelsea Ju
"""
import sys, re, pysam, os, random, argparse
# chromosome size: from chr1 - chr23, X, Y, mitochondira
CHR_SIZE = [247199719, 242751149, 199446827, 191263063, 180837866,
170896993, 158821424, 146274826, 140442298, 135374737,
134452384, 132289534, 114127980, 106360585, 100338915,
88822254, 78654742, 76117153, 63806651, 62435965,
46944323, 49528953, 154913754, 57741652, 16569
]
"""
convert the chromosome name to an index
0 = chr1,
22 = chrX,
23 = ChrY,
24 = Mitochondria
"""
def get_chr_index(name):
name = name.lower()
match_chr_number = re.match(r"\D*(\d+)", name)
match_chr_X = re.match(r"\D*(x)", name)
match_chr_Y = re.match(r"\D*(y)", name)
match_chr_M = re.match(r"\D*(m)", name)
if(match_chr_number):
return int(match_chr_number.group(1)) - 1
elif(match_chr_X):
return 22
elif(match_chr_Y):
return 23
elif(match_chr_M):
return 24
else:
print ("unknown input %s", name)
sys.exit(2)
"""
reverse function of get_chr_index
given an index, return the chr name
"""
def get_chr_name(index):
if(index < 22):
return "chr" + str(index+1)
elif(index == 22):
return "chrX"
elif(index == 23):
return "chrY"
elif(index == 24):
return "chrM"
else:
print ("unknown input %s", str(index))
sys.exit(2)
"""
using samtool to sort the bam file
equivalent to samtool sort bam sort.bam
after the sorting, create an index file on the sort.bam
"""
def sort_bam_file(bam_file, outputPrefix):
## get the file prefix
prefix = "accepted_hits"
prefix_match = re.match(r"(.*).bam", bam_file)
if(prefix_match):
prefix = prefix_match.group(1)
# sort the bam file
sort_bam = prefix + "_sorted"
pysam.sort(bam_file, sort_bam)
sort_bam = sort_bam + ".bam"
# index the sort bam file
pysam.index(sort_bam)
print ""
print "Writing Sorted Bam File : %s" %(sort_bam)
print "Writing Index Sorted Bam File : %s.bai" %(sort_bam)
return sort_bam
"""
The main function of the script:
1. it fetches the reads of a given chromosome name from the sorted bam file
2. for each read, it marks the positions the read covered
if the read mapped to multiple places in the given chromosome, all positions are marked
however, each position is only marked once by one read.
for example, readA has three alignments (1-100, 1-40:101-160, 201-300),
then position 1-160 and 201-300 are marked once (+1) by this read
note: because of the counting method, each read is considered as single read.
pair-end properties (such as "read mapped in proper pair") are not taken into consideration.
in another word, accepted reads (all in accepted_hit.bam) are not discarded.
"""
def read_counter(sorted_input, chromosome_name, threshold):
chr_size = CHR_SIZE[get_chr_index(chromosome_name)]
counts_array = [0]*chr_size
unique_read_name = {}
samfile = pysam.Samfile( sorted_input, "rb" )
for read in samfile.fetch(chromosome_name, 0, chr_size):
read_name = read.qname
# applies to those reads that passed the specified mapq threshold
if(read.mapq > threshold):
if(not unique_read_name.has_key(read_name)):
unique_read_name[read_name] = []
# collect a list of positions the reads aligned to, including the positions resulted in multiple alignments
unique_read_name[read_name].extend(read.positions)
# each read has a list of positions it mapped to
# each position is updated only once by one read:
# the duplicated positions are removed
# update counts_array by the sorted list of positions
for k,v in unique_read_name.items():
sort_v = sorted(set(v))
for sv in sort_v:
counts_array[sv] +=1
samfile.close()
return counts_array
"""
write the read counts to file
"""
def output_array(array, chromosome_name, outfile):
header = chromosome_name + "_size_" + str(len(array))
total_count = sum(array)
out_fh = open(outfile, 'w')
out_fh.write("%s\n" % (header))
if(total_count > 0):
position = 0
for a in array:
position += 1
if(a > 0):
out_fh.write("%d\t%d\n" %(position, a))
out_fh.close()
print "Writing Read Counts to file : %s" %(outfile)
def main(parser):
options = parser.parse_args()
chromosome_name = options.chromosome
input = options.bamFile
output = options.outPrefix
threshold = options.threshold
## start counting the reads
sorted_input = sort_bam_file(input, output)
counts_array = read_counter(sorted_input, chromosome_name, threshold)
## output data
outfile = output + chromosome_name + "_count.obj"
output_array(counts_array, chromosome_name, outfile)
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog='position_coverage_counter.py')
parser.add_argument("-t", "--threshold", dest="threshold", type=int, default=0, help="mapQ cutoff [OPTIONAL]")
parser.add_argument("-c", "--chromosome", dest="chromosome", type=str, help="chromosome name, ex chr1", required = True)
parser.add_argument("-i", "--input", dest="bamFile", type=str, help="bam file name, ex accepted_hit.bam", required = True)
parser.add_argument("-o", "--output", dest="outPrefix", type=str, help="prefix or directory of output files", required = True)
main(parser)