-
Notifications
You must be signed in to change notification settings - Fork 11
/
annotation_pie.py
executable file
·394 lines (322 loc) · 14.3 KB
/
annotation_pie.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
#!/usr/bin/env python
from optparse import OptionParser
import math, os, re, sys, subprocess, tempfile
import pysam
import ggplot
################################################################################
# annotation_bars.py
#
# Count aligned reads to various annotation classes and make pie charts.
################################################################################
################################################################################
# main
################################################################################
def main():
usage = 'usage: %prog [options] <hg19|mm9> <bam1,bam2,...>'
parser = OptionParser(usage)
parser.add_option('-a', dest='annotations', default='rrna,smallrna,cds,utrs_3p,utrs_5p,pseudogene,lncrna,introns,intergenic', help='Comma-separated list of annotation classes to include [Default: %default]')
parser.add_option('-o', dest='output_prefix', default='annotation', help='Output file prefix [Default: %default]')
parser.add_option('-p', dest='paired_stranded', action='store_true', default=False, help='Paired end stranded reads, so split intersects by XS tag and strand [Default: %default]')
parser.add_option('-t', dest='title', default='', help='Plot title [Default: %default]')
parser.add_option('-u', dest='unstranded', action='store_true', default=False, help='Unstranded reads, so count intergenic and renormalize to lessen the impact of double counting [Default: %default]')
(options,args) = parser.parse_args()
if len(args) == 2:
genome = args[0]
bam_files = args[1].split(',')
else:
parser.error(usage)
if genome == 'hg19':
assembly_dir = '%s/research/common/data/genomes/hg19/assembly' % os.environ['HOME']
if options.paired_stranded:
annotation_dir = '%s/pie_stranded' % os.environ['GENCODE']
else:
annotation_dir = '%s/pie_unstranded' % os.environ['GENCODE']
elif genome == 'mm9':
assembly_dir = '%s/research/common/data/genomes/mm9/assembly' % os.environ['HOME']
if options.paired_stranded:
print >> sys.stderr, 'Stranded annotation BEDs dont exist for mm9'
exit(1)
else:
annotation_dir = '/n/rinn_data1/indexes/mouse/mm9/annotations/dk_pie'
else:
parser.error('Genome must specify hg19 or mm9.')
if options.paired_stranded:
# split bam files by strand
for bam_file in bam_files:
split_bam_xs(bam_file)
annotation_classes = set(options.annotations.split(','))
############################################
# annotation lengths
############################################
genome_length = count_genome(assembly_dir)
annotation_lengths = {}
for ann in annotation_classes:
if ann != 'intergenic':
annotation_bed = '%s/%s.bed' % (annotation_dir,ann)
if os.path.isfile(annotation_bed):
annotation_lengths[ann] = annotation_length(annotation_bed, assembly_dir)
else:
parser.error('Cannot find annotation BED %s' % annotation_bed)
if 'intergenic' in annotation_classes:
other_annotations_summed = sum(annotation_lengths.values())
annotation_lengths['intergenic'] = genome_length - other_annotations_summed
############################################
# annotation read counts
############################################
genome_reads = 0
for bam_file in bam_files:
genome_reads += count_bam(bam_file)
annotation_reads = {}
for ann in annotation_classes:
if ann != 'intergenic':
annotation_bed = '%s/%s.bed' % (annotation_dir,ann)
annotation_reads[ann] = 0
for bam_file in bam_files:
annotation_reads[ann] += count_intersection(bam_file, annotation_bed, options.unstranded, options.paired_stranded)
if 'intergenic' in annotation_classes:
other_annotations_summed = sum(annotation_reads.values())
annotation_reads['intergenic'] = genome_reads - other_annotations_summed
if options.unstranded:
intergenic_reads_sub = annotation_reads['intergenic']
intergenic_reads = 0
for bam_file in bam_files:
intergenic_reads += count_sans_intersection(bam_file, '%s/../gencode.v18.annotation.prerna.gtf' % annotation_dir)
if options.paired_stranded:
for bam_file in bam_files:
os.remove(bam_file[:-4] + '_p.bam')
os.remove(bam_file[:-4] + '_m.bam')
############################################
# table
############################################
annotation_labels = {'rrna':'rRNA', 'smallrna':'smallRNA', 'cds':'CDS', 'utrs_3p':'3\'UTR', 'utrs_5p':'5\'UTR', 'pseudogene':'Pseudogene', 'lncrna':'lncRNA', 'exons':'Exons', 'introns':'Introns', 'intergenic':'Intergenic', 'mrna':'mRNA'}
reads_sum = float(sum(annotation_reads.values()))
lengths_sum = float(sum(annotation_lengths.values()))
annotation_ratio = {}
counts_out = open('%s_counts.txt' % options.output_prefix, 'w')
for ann in annotation_classes:
read_pct = annotation_reads[ann]/reads_sum
length_pct = annotation_lengths[ann]/lengths_sum
if read_pct > 0:
annotation_ratio[ann] = math.log(read_pct/length_pct,2)
else:
annotation_ratio[ann] = math.log((1+annotation_reads[ann])/(1+reads_sum),2)
cols = (annotation_labels[ann], annotation_reads[ann], read_pct, length_pct, annotation_ratio[ann])
print >> counts_out, '%10s %8d %6.4f %6.4f %5.2f' % cols
counts_out.close()
############################################
# pie chart
############################################
pie_df = {'dummy':[], 'annotation':[], 'count':[]}
for ann in annotation_classes:
pie_df['dummy'].append('.')
pie_df['annotation'].append(annotation_labels[ann])
pie_df['count'].append(annotation_reads[ann])
out_pdf = '%s_pie.pdf' % options.output_prefix
ggplot.plot('%s/annotation_pie_pie.r'%os.environ['RDIR'], pie_df, [options.title, out_pdf], df_file=out_pdf[:-1])
############################################
# read:length ratio
############################################
ratio_df = {'annotation':[], 'ratio':[]}
for ann in annotation_classes:
ratio_df['annotation'].append(annotation_labels[ann])
ratio_df['ratio'].append(annotation_ratio[ann])
ggplot.plot('%s/annotation_pie_ratios.r'%os.environ['RDIR'], ratio_df, [options.title, '%s_ratios.pdf'%options.output_prefix])
################################################################################
# annotation_length
#
# Input
# bed_file: Annotation BED file
#
# Output
# alength: Summed lengths of the annotations.
################################################################################
def annotation_length(bed_file, assembly_dir):
if assembly_dir.find('hg19') != -1:
gaps_file = '%s/hg19_gaps.bed' % assembly_dir
elif assembly_dir.find('mm9') != -1:
gaps_file = '%s/mm9_gaps.bed' % assembly_dir
else:
print >> sys.stderr, 'Bad assembly directory'
exit(1)
alength = 0
p = subprocess.Popen('subtractBed -a %s -b %s' % (bed_file,gaps_file), shell=True, stdout=subprocess.PIPE)
for line in p.stdout:
a = line.split('\t')
alength += int(a[2]) - int(a[1])
p.communicate()
return alength
################################################################################
# count_bam
#
# Input
# bam_file:
#
# Output
# read_count: Number of aligned fragments.
################################################################################
def count_bam(bam_file, skip_spliced=False):
read_count = 0
bam_in = pysam.Samfile(bam_file, 'rb')
for aligned_read in bam_in:
# high quality
if aligned_read.mapq > 0:
# we're not skipping spliced or it's not spliced
if not skip_spliced or not spliced(aligned_read):
# not a dumb chromosome
chrom = bam_in.getrname(aligned_read.tid)
if not chrom.startswith('chrUn') and chrom.find('random') == -1 and chrom.find('hap') == -1:
if aligned_read.is_paired:
read_count += 0.5/aligned_read.opt('NH')
else:
read_count += 1.0/aligned_read.opt('NH')
bam_in.close()
return read_count
################################################################################
# count_intersection
#
# Input
# bam_file: Read alignment BAM file
# bed_file: Annotation BED file
# paired_stranded: Reads are paired and stranded
# introns: Counting introns, so ignore spliced reads
#
# Output
# reads: The number of reads (corrected for multi-mappers)
# overlapping the annotation in the BED file.
################################################################################
def count_intersection(bam_file, bed_file, unstranded, paired_stranded, introns=False):
intersect_bam_fd, intersect_bam_file = tempfile.mkstemp(dir='%s/research/scratch/temp' % os.environ['HOME'])
if paired_stranded:
# make split bed temp files
bedp_fd, bedp_file = tempfile.mkstemp()
bedm_fd, bedm_file = tempfile.mkstemp()
# split bed file
split_bed(bed_file, bedp_file, bedm_file)
# get split BAM file names
bamp_file = bam_file[:-4] + '_p.bam'
bamm_file = bam_file[:-4] + '_m.bam'
# count +
subprocess.call('intersectBed -f 0.5 -abam %s -b %s > %s' % (bamp_file,bedp_file,intersect_bam_file), shell=True)
readsp = count_bam(intersect_bam_file, skip_spliced=introns)
# count -
subprocess.call('intersectBed -f 0.5 -abam %s -b %s > %s' % (bamm_file,bedm_file,intersect_bam_file), shell=True)
readsm = count_bam(intersect_bam_file, skip_spliced=introns)
# sum + and -
reads = readsp + readsm
# clean temp
os.close(bedp_fd)
os.remove(bedp_file)
os.close(bedm_fd)
os.remove(bedm_file)
else:
strand_str = '-s'
if unstranded:
strand_str = ''
# intersect
subprocess.call('intersectBed -f 0.5 %s -abam %s -b %s > %s' % (strand_str,bam_file,bed_file,intersect_bam_file), shell=True)
# count
reads = count_bam(intersect_bam_file, skip_spliced=introns)
# clean
os.close(intersect_bam_fd)
os.remove(intersect_bam_file)
return reads
################################################################################
# count_sans_intersection
#
# Input
# bam_file: Read alignment BAM file
# bed_file: Annotation BED file
#
# Output
# reads: The number of reads (corrected for multi-mappers) not overlapping
# the annotation in the BED file.
################################################################################
def count_sans_intersection(bam_file, bed_file):
intersect_bam_fd, intersect_bam_file = tempfile.mkstemp(dir='%s/research/scratch/temp' % os.environ['HOME'])
# intersect
subprocess.call('intersectBed -s -v -f 0.5 -abam %s -b %s > %s' % (bam_file,bed_file,intersect_bam_file), shell=True)
# count
reads = count_bam(intersect_bam_file)
# clean
os.close(intersect_bam_fd)
os.remove(intersect_bam_file)
return reads
################################################################################
# count_genome
#
# Output
# glength: Length of the human genome assembly minus gaps.
################################################################################
def count_genome(assembly_dir):
if assembly_dir.find('hg19') != -1:
chrom_file = '%s/human.hg19.genome' % assembly_dir
gaps_file = '%s/hg19_gaps.bed' % assembly_dir
elif assembly_dir.find('mm9') != -1:
chrom_file = '%s/mouse.mm9.genome' % assembly_dir
gaps_file = '%s/mm9_gaps.bed' % assembly_dir
else:
print >> sys.stderr, 'Bad assembly directory'
exit(1)
# count chromosome sizes
glength = 0
for line in open(chrom_file):
a = line.split()
chrom = a[0]
if not chrom.startswith('chrUn') and chrom.find('random') == -1 and chrom.find('hap') == -1:
glength += int(a[1])
# subtract gaps
for line in open(gaps_file):
a = line.split()
chrom = a[0]
if not chrom.startswith('chrUn') and chrom.find('random') == -1 and chrom.find('hap') == -1:
glength -= int(a[2]) - int(a[1])
return glength
################################################################################
# spliced
#
# Return true if the read is spliced.
################################################################################
def spliced(aligned_read):
spliced = False
for code,size in aligned_read.cigar:
if code == 3:
spliced = True
return spliced
################################################################################
# split_bam_xs
#
# Split the alignments in the given BAM file into plus and minus strand.
################################################################################
def split_bam_xs(bam_file):
bamp_file = bam_file[:-4] + '_p.bam'
bamm_file = bam_file[:-4] + '_m.bam'
bam_in = pysam.Samfile(bam_file, 'rb')
bamp_out = pysam.Samfile(bamp_file, 'wb', template=bam_in)
bamm_out = pysam.Samfile(bamm_file, 'wb', template=bam_in)
for aligned_read in bam_in:
if aligned_read.opt('XS') == '+':
bamp_out.write(aligned_read)
else:
bamm_out.write(aligned_read)
bam_in.close()
bamp_out.close()
bamm_out.close()
################################################################################
# split_bed
################################################################################
def split_bed(bed_file, bedp_file, bedm_file):
bedp_out = open(bedp_file, 'w')
bedm_out = open(bedm_file, 'w')
for line in open(bed_file):
a = line.split('\t')
if a[5] == '+':
print >> bedp_out, line,
else:
print >> bedm_out, line,
bedp_out.close()
bedm_out.close()
################################################################################
# __main__
################################################################################
if __name__ == '__main__':
main()