development release: conversion of ReadDataset to use BAM files
[erange.git] / runStrandedAnalysis.py
diff --git a/runStrandedAnalysis.py b/runStrandedAnalysis.py
new file mode 100644 (file)
index 0000000..55c87ca
--- /dev/null
@@ -0,0 +1,129 @@
+import sys
+import optparse
+import ReadDataset
+from commoncode import writeLog
+from checkrmask import checkrmask
+from geneMrnaCounts import geneMrnaCounts
+from geneMrnaCountsWeighted import geneMrnaCountsWeighted
+from getallgenes import getallgenes
+from normalizeFinalExonic import normalizeFinalExonic
+from normalizeExpandedExonic import normalizeExpandedExonic
+from findall import findall, RegionFinder
+
+VERSION = "1.0"
+
+def main(argv=None):
+    if not argv:
+        argv = sys.argv
+
+    print "runStrandedAnalysis: version %s" % VERSION
+    usage = "usage: python runStrandedAnalysis.py genome rdsprefix repeatmaskdb bpradius"
+
+    parser = getParser(usage)
+    (options, args) = parser.parse_args(argv[1:])
+
+    if len(args) < 4:
+        print usage
+        sys.exit(1)
+
+    genome = args[0]
+    rdsprefix = args[1]
+    repeatmaskdb = args[2]
+    bpradius = args[3]
+
+    runStrandedAnalysis(genome, rdsprefix, repeatmaskdb, bpradius)
+
+
+def getParser(usage):
+    parser = optparse.OptionParser(usage=usage)
+
+    return parser
+
+
+def runStrandedAnalysis(genome, rdsprefix, repeatmaskdb, bpradius):
+    """ based on original script runStrandedAnalysis.sh
+        usage: runStrandedAnalysis.sh genome rdsprefix repeatmaskdb bpradius
+               where rdsprefix is the name of the rds file without the .rds extension
+               use "none" for the repeatmaskdb if you do not have one
+    """
+
+    rdsfile = "%s.rds" % rdsprefix
+    logfile = "rna.log"
+
+    # log the parameters
+    message = "with parameters: %s %s %s %s" % (genome, rdsprefix, repeatmaskdb, bpradius)
+    writeLog(logfile, "runStrandedAnalysis.py", message)
+
+    # count the unique reads falling on the gene models ; the nomatch files are 
+    # mappable reads that fell outside of the Cistematic gene models and not the 
+    # unmappable of Eland (i.e, the "NM" reads)
+    uniquecountfilename = "%s.uniqs.count" % rdsprefix
+    geneMrnaCounts(genome, rdsfile, uniquecountfilename, trackStrand=True, cachePages=1, markGID=True)
+
+    # calculate a first-pass RPKM to re-weigh the unique reads,
+    # using 'none' for the splice count
+    initialrpkmfilename = "%s.firstpass.rpkm" % rdsprefix
+    RDS = ReadDataset.ReadDataset(rdsfile, verbose=True, cache=True, reportCount=False)
+    (ucount, mcount, scount) = RDS.getCounts(multi=True, splices=True, reportCombined=False)
+    readCounts = {}
+    readCounts["uniq"] = ucount
+    readCounts["splice"] = mcount
+    readCounts["multi"] = scount
+    normalizeExpandedExonic(genome, readCounts["uniq"], uniquecountfilename, "none", initialrpkmfilename, doCache=True)
+
+    # recount the unique reads with weights calculated during the first pass
+    initialrpkmfilename = "%s.firstpass.rpkm" % rdsprefix
+    uniquerecountfilename = "%s.uniqs.recount" % rdsprefix
+    geneMrnaCountsWeighted(genome, rdsfile, initialrpkmfilename, uniquerecountfilename, withUniqs=True, cachePages=1, ignoreSense=False)
+
+    # count splice reads
+    splicecountfilename = "%s.splices.count" % rdsprefix
+    geneMrnaCounts(genome, rdsfile, splicecountfilename, trackStrand=True, doSplices=True, doUniqs=False, cachePages=1)
+
+    # find new regions outside of gene models with reads piled up 
+    newregionfilename = "%s.newregions.txt" % rdsprefix
+    regionFinder = RegionFinder("RNAFARP", minHits=1, withFlag="NM", strandfilter="plus")
+    findall(regionFinder, rdsfile, newregionfilename, logfilename=logfile, rnaSettings=True, cachePages=1, useMulti=False)
+
+    regionFinder = RegionFinder("RNAFARM", minHits=1, withFlag="NM", strandfilter="plus")
+    findall(regionFinder, rdsfile, newregionfilename, logfilename=logfile, rnaSettings=True, cachePages=1, useMulti=False, outputMode="a")
+
+    # filter out new regions that overlap repeats more than a certain fraction
+    newregionfilename = "%s.newregions.txt" % rdsprefix
+    outFileName = "%s.newregions.repstatus" % rdsprefix
+    goodFileName = "%s.newregions.good" % rdsprefix
+    checkrmask(repeatmaskdb, newregionfilename, outFileName, goodFileName, startField=1, cachePages=1, logfilename=logfile)
+
+    #TODO: these calls look wrong
+    # Alternative 2: use a precomputed list of "new" regions (outside of gene models)
+    #python $ERANGEPATH/regionCounts.py $3 $2.nomatch.bed $2.newregions.good $2.stillnomatch.bed
+    #python $ERANGEPATH/regionCounts.py $3 $2.rds $2.newregions.good
+
+    # map all candidate regions that are within a given radius of a gene in bp
+    candidatefilename = "%s.candidates.txt" % rdsprefix
+    getallgenes(genome, goodFileName, candidatefilename, maxRadius=bpradius, trackFar=True, doCache=True, trackStrand=True)
+
+    expandedRPKMfilename = "%s.expanded.rpkm" % rdsprefix
+    # calculate expanded exonic read density
+    acceptedfilename = "%s.accepted.rpkm" % rdsprefix
+    try:
+        candidatefile = open(candidatefilename)
+        candidateLines = candidatefile.readlines()
+        candidatefile.close()
+    except IOError:
+        candidateLines = []
+
+    normalizeExpandedExonic(genome, readCounts["uniq"], uniquerecountfilename, splicecountfilename, expandedRPKMfilename, candidateLines=candidateLines, acceptedfilename=acceptedfilename,
+                            doCache=True)
+
+    # weigh multi-reads
+    multicountfilename = "%s.multi.count" % rdsprefix
+    geneMrnaCountsWeighted(genome, rdsfile, expandedRPKMfilename, multicountfilename, withMulti=True, acceptfile=acceptedfilename, cachePages=1)
+
+    # calculate final exonic read density
+    outfilename = "%s.final.rpkm" % rdsprefix
+    normalizeFinalExonic(readCounts, expandedRPKMfilename, multicountfilename, outfilename, reportFraction=True, doCache=True, writeGID=True)
+
+
+if __name__ == "__main__":
+    main(sys.argv)
\ No newline at end of file