Source

RNA-seq pipeline / evenness_qclib.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
#!/usr/bin/env python

"""
Run help for information
last modified by Jianxign Feng ( Wed Mar 23 13:11:53 CST 2011 )
"""

import sys
import argparse
import textwrap
import re
from operator import itemgetter

def CmpInterval (interv1, interv2):
    return interv1.Less(interv2)

class Interval:
    start = -1
    end = -1

    def Less(self, interv2):
        if (self.start < interv2.start):
            return -1
        elif (self.start > interv2.start):
            return 1
        elif (self.end < interv2.end):
            return -1
        else:
            return 1


class Isoform(Interval):
    name = ""
    chrom = ""
    strand = ""
    exons = None
    partsum = None
    belongToGene = None

    def PartialSum(self):
        """ Just for speed """
        self.partsum = [0 for i in range(len(self.exons)+1)]
        for i in range(len(self.partsum))[1:]:
            self.partsum[i] = self.partsum[i-1] + self.exons[i-1].end - self.exons[i-1].start

    def RelativePos(self, pos):
        idx = binSearchInterval(self.exons, pos) - 1

        # This read does not belong to this gene
        if (idx < 0 or self.exons[idx].end <= pos):
            return -1

        #print pos,self.partsum[idx],self.exons[idx].start

        #self.Print()

        relpos = self.partsum[idx] + pos - self.exons[idx].start
        #print relpos
        #print float(relpos) / self.partsum[-1]

        if (self.strand == "-"):
            relpos = self.partsum[-1] - relpos
        return float(relpos) / self.partsum[-1]

    def Print(self):
        print self.name,"\t",self.start,"\t",self.end,"\t",len(self.exons),"   ",
        for each in self.exons:
            print each.start,",",each.end,"\t",
        print self.partsum
        print id(self.partsum)

    def UnionExon(self):
        """ Taking union of all the exons """

        self.exons.sort(cmp=CmpInterval)

        pre_idx = 0
        for idx in range(len(self.exons))[1:]:
            if (self.exons[idx].start < self.exons[pre_idx].end):
                if (self.exons[idx].end > self.exons[pre_idx].end):     # In case an interval is completely included into another one
                    self.exons[pre_idx].end = self.exons[idx].end
                self.exons[idx].start = -1
            else:
                pre_idx = idx
        
        good_idx = 0
        for idx in range(len(self.exons))[0:]:
            if (self.exons[idx].start != -1):
                self.exons[good_idx] = self.exons[idx]
                good_idx += 1
        self.exons = self.exons[0:good_idx]

        self.start = self.exons[0].start
        self.end = self.exons[-1].end
        self.PartialSum()
     
class HandlerBase:
    """ The base for handling refgenes and reads """
    def Init(self):
        return
    def InitLoadRefGene(self):
        return
    def OnAnExon(self, chr, strand, gene_id, tran_id, start, end):
        return
    def FinishLoadRefGene(self):
        return
    def InitLoadReads(self):
        return
    def OnARead(self, aligned, chr, strand, pos, sequence, quality):
        return
    def FinishLoadReads(self):
        return
    def CleanUp(self):    
        return

class Eveness(HandlerBase):
    # Genes indexed by their gene_id
    rawGenes = {}

    # Genes with isoforms on different chromosomes
    diffChrGene = {}

    # Due to genes with isoforms on different chromosomes, some exons will be skipped
    skippedExonCnt = 0

    # All the ref genes with overlapped removed
    # and if there are two isoforms belonging to different chromosomes, only one of them is kept
    # This variable is used to calculate reads distribution
    cleanGenes = {}

    # Number of reads belonging to clean genes
    mappedOnCleanGeneCnt = 0

    # The relative position count
    relPosCnt = [0 for i in range(101)]

    lastGene = None
    lastGeneID = ""
    lastChr = ""
    lastPos = -1
    lastRelPos = -1
    
    # Eveness
    def FinishLoadRefGene(self):
        rawGenes = self.rawGenes
        cleanGenes = self.cleanGenes

        # for gene_id in self.diffChrGene.keys():
        #     print "gene %s's Transcripts on chromosome %s, " % (gene_id, rawGenes[gene_id].chrom),
        # print "was kept"
        print "Warning,", self.skippedExonCnt, "exons have been skipped due to genes with isoforms on different chromosomes."

        print "Regrouping clean genes by chromosome"
        for gid, gene in rawGenes.iteritems():
            gene.UnionExon()
            if (gene.chrom not in cleanGenes.keys()):
                cleanGenes[gene.chrom] = []
            cleanGenes[gene.chrom].append(gene)

        print "Sorting and removing genes that are overlapped for clean genes"
        removed_cnt = 0
        for chr in cleanGenes.keys():
            genes = cleanGenes[chr]
            genes.sort(CmpInterval)
            #for idx in range(len(genes))[1:]:
            #    if (genes[idx].start < genes[idx-1].end):
            #        genes[idx].start = -1
            #        genes[idx].end = genes[idx-1].end
            good_idx = 0
            for idx in range(len(genes)):
                if (genes[idx].start != -1):
                    genes[good_idx] = genes[idx]
                    good_idx += 1
            removed_cnt += len(genes) - good_idx
            cleanGenes[chr] = genes[0:good_idx]
        print "%d genes has been removed for clean genes due to overlap" % (removed_cnt)

    # Eveness
    def OnAnExon(self, chr, strand, gene_id, tran_id, start, end):
        # For rawGenes
        rawGenes = self.rawGenes
        exon = Interval()
        exon.start = start
        exon.end = end
        if (gene_id == self.lastGeneID):
            gene = self.lastGene
        elif (gene_id not in rawGenes.keys()):
            gene = Isoform()
            rawGenes[gene_id] = gene
            gene.name = gene_id 
            gene.strand = strand
            gene.chrom = chr
            gene.exons = []
        else:
            gene = rawGenes[gene_id]
        self.lastGene = gene
        self.lastGeneID = gene_id

        if (chr != gene.chrom):
            self.skippedExonCnt += 1
            self.diffChrGene[gene_id] = rawGenes[gene_id].chrom
            return

        gene.exons.append(exon)
        exon.belongToIsoform = gene

    # Eveness
    def OnARead(self, aligned, chr, strand, pos, sequence, quality):
        """ For relPosCnt. Get the relative position of the read on the corresponding gene """

        if (chr == self.lastChr and pos == self.lastPos):
            relpos = self.lastRelPos
        else:
            self.lastChr = chr
            self.lastPos = pos
            self.lastRelPos = -1

            if (chr not in self.cleanGenes.keys()):
                return False

            curr_genes = self.cleanGenes[chr]
            gidx = binSearchInterval(curr_genes, pos) - 1
            if (gidx < 0):
                return False
            #print pos, chr, gidx, len(curr_genes), curr_genes[gidx].name, curr_genes[gidx].start, curr_genes[gidx].end
            if (curr_genes[gidx].end <= pos):
                # The read does not belong to this gene
                return False
            relpos = curr_genes[gidx].RelativePos(pos);
            relpos = int(relpos * 100)

            self.lastRelPos = relpos

        if (relpos < 0):
            return False

        self.relPosCnt[relpos] += 1
        self.mappedOnCleanGeneCnt += 1
        return True

    # Eveness
    def FinishLoadReads(self):
        print "Number of reads belonging to clean genes (used to calculate relPosCnt):",
        print self.mappedOnCleanGeneCnt
        print "relPosCnt:",
        print self.relPosCnt[0:100]
        return self.relPosCnt[0:100]



def binSearchInterval(intervals, pos):
    """ Given a sorted interval and a position find
        out the least interval with start position
        greater than the given position. Return len(intervals)
        if the start position of the last element in intervals
        is less than pos"""

    low = 0
    high = len(intervals) - 1
    while (True):
        mid = int((low + high) / 2)
        #print pos,low,mid,high,len(intervals)
        #print pos,intervals[low].start,intervals[mid].start,intervals[high].start
        if (pos < intervals[mid].start):
            high = mid-1
        elif (pos > intervals[mid].start):
            low = mid+1
        elif (pos == intervals[mid].start):
            idx = mid
            break
        if (low >= high):
            idx = mid
            break

    # To deal with the case that two intervals have the same start position
    while (idx < len(intervals) and pos >= intervals[idx].start):
        idx += 1
    while (idx > 0 and pos < intervals[idx-1].start):
        idx -= 1

    #if (idx > 0 and idx < len(intervals)):
    #    print pos, idx, intervals[idx-1].start, intervals[idx-1].end, intervals[idx].start, intervals[idx].end

    return idx


def getGenes(openedGeneFile, summary):
    """ Load the gene table """

    summary.InitLoadRefGene()

    line_cnt = 0
    all_exon_cnt = 0

    print "Loading genes ..."

    line_sum = -1
    for line_sum,line in enumerate(openedGeneFile):
        pass
    line_sum += 1
    openedGeneFile.seek(0)

    one_tenth=line_sum/10
    progress_tenth=0

    for line in openedGeneFile:
        line_cnt = line_cnt + 1

        if (line_cnt % one_tenth == 0):
            # print r"%"+"%d\t - %d lines have been scanned" % (progress_tenth,line_cnt)
            progress_tenth += 10

        line = line.strip()

        fields = line.split('\t')
        if (fields[2] != "exon"):
            continue

        all_exon_cnt += 1

        startidx = fields[8].find('gene_id "') + len('gene_id "')
        endidx = fields[8].find('"', startidx)

        gene_id = fields[8][startidx:endidx]
        start = int(fields[3])
        end = int(fields[4])
        chr = fields[0]
        strand = fields[6]

        summary.OnAnExon(chr, strand, gene_id, "ignore", start, end)

    print "Totally scanned %d lines, %d exons" % (line_cnt, all_exon_cnt)

    summary.FinishLoadRefGene()

def loadReadsBowtieSAM(openedReadFile, summary):
    """ Load reads in SAM format output by Bowtie"""

    summary.InitLoadReads()

    print "Loading reads ..."

    end_len = 0
    line_cnt = 0
    for line in openedReadFile:
        line_cnt = line_cnt + 1
        if (line[0] == "@"):
            continue

        line = line.strip()
        fields = line.split('\t')

        flat = int(fields[1])
        aligned = True
        if (flat & 4):
            aligned = False

        chr = fields[2]
        pos = int(fields[3])
        strand = "+"
        sequence = fields[9]
        qty = fields[10]

        summary.OnARead(aligned, chr, strand, pos, sequence, qty)


    print "Loading reads done"
    print "%d lines have been scanned" % (line_cnt)
    
    return summary.FinishLoadReads()

   
def process_command_line(argv):
    """ Processing command line """

    if argv is None:
        argv = sys.argv[1:]

    parser = argparse.ArgumentParser(description='Version 0.0.1. Given ref gene list and mapped short reads. Get the reads summary. ')

    # Manual:
    parser.add_argument('openedReads', nargs='?', default=sys.stdin, type=argparse.FileType('r'), help='Mapped reads by Bowtie in SAM format')
    parser.add_argument('refGenes', type=argparse.FileType('r'), help='Ref genes in gtf format.')
    parser.add_argument('outputFile', type=argparse.FileType('w'), help='A file for output of the number of mapped reads on each gene. \
            If a read is mapped to two overlapping genes, count the read twice.')

    args = parser.parse_args(argv)

    return args



def evenness_output(relPosCnt,output):
    print "start graphing.."
    print >>output,"relPosCnt"
    print >>output,",".join(map(str,relPosCnt))
    with open(output.name+".r","w") as output_script:
        print >>output_script,"pdf('%s.pdf')"%output.name
        print >>output_script,"x=c(%s);"%(",".join(map(str,relPosCnt)))
        print >>output_script,"plot(x,type='l');"
        print >>output_script,"dev.off();"    
    print "success!!"
def main(argv=None):
    """ The main entrance of the program. """

    args = process_command_line(argv)

    # summary = HandlerGroup()
    # summary.AddHandler(Eveness())

    evenness_qc=Eveness()
    
    evenness_qc.Init()
    getGenes(args.refGenes, evenness_qc)
    relPos=loadReadsBowtieSAM(args.openedReads, evenness_qc)
    evenness_output(relPos,args.outputFile)
    evenness_qc.CleanUp()

    return(0)

if __name__ == '__main__':
    status = main()
    sys.exit(status)