def drawHistogram(data,
                  mainTitle,
                  xTitle,
                  yTitle,
                  xLim,
                  yLim=None,
                  color='cadetblue2'):
    from proto.RSetup import robjects

    hist = robjects.r.hist
    if yLim:
        hist(robjects.FloatVector(data),
             main=mainTitle,
             xlab=xTitle,
             ylab=yTitle,
             xlim=robjects.FloatVector(xLim),
             ylim=robjects.FloatVector(yLim),
             col=color)
    else:
        hist(robjects.FloatVector(data),
             main=mainTitle,
             xlab=xTitle,
             ylab=yTitle,
             xlim=robjects.FloatVector(xLim),
             col=color)
    def _combineResults(self):
        StatisticDictSumResSplittable._combineResults(self)
        self._result['t1prop'] = float(
            self._result['t1coverage']) / self._result['NumBps']
        self._result['t2prop'] = float(
            self._result['t2coverage']) / self._result['NumBps']
        self._result[
            'ExpBothBpProportionGivenIndividualBinCoverage'] = self._result[
                'ExpBothBpCoverageGivenIndividualBinCoverage'] / self._result[
                    'NumBps']
        self._result[
            'ExpBothBpProportionFromGlobalIndividualCoverage'] = self._result[
                't1prop'] * self._result['t2prop']

        from proto.RSetup import robjects, r
        t1Props = [x['t1prop'] for x in self._childResults]
        t2Props = [x['t2prop'] for x in self._childResults]

        if len(t1Props) > 1:
            correlation = float(
                r.cor(robjects.FloatVector(t1Props),
                      robjects.FloatVector(t2Props)))
            import numpy
            if numpy.isnan(correlation):
                correlation = None
                correlationPval = None
            else:
                correlationPval = r(
                    'function(x,y){res=cor.test(x,y); return(res$p.value)}')(
                        robjects.FloatVector(t1Props),
                        robjects.FloatVector(t2Props))

            #print 'CORR: ',type(correlation), correlation
        else:
            correlationPval = correlation = None

        self._result['IndividualCoveragePerBinCorrelation'] = correlation
        self._result[
            'IndividualCoveragePerBinCorrelationPvalue'] = correlationPval

        self._result['ObsBpProportionOverlap'] = (
            float(self._result['ObsBpOverlap']) /
            self._result['NumBps']) if self._result['NumBps'] > 0 else None
        self._result['RatioOfObsToExpGivenGlobalCoverages'] = (
            self._result['ObsBpProportionOverlap'] /
            self._result['ExpBothBpProportionFromGlobalIndividualCoverage']
        ) if self._result[
            'ExpBothBpProportionFromGlobalIndividualCoverage'] > 0 else None
        self._result['RatioOfObsToExpGivenIndividualBinCoverages'] = (
            self._result['ObsBpProportionOverlap'] /
            self._result['ExpBothBpProportionGivenIndividualBinCoverage']
        ) if self._result[
            'ExpBothBpProportionGivenIndividualBinCoverage'] > 0 else None
def drawXYPlot(xData, yData, plotType, xLim, yLim, mainTitle, xTitle, yTitle):
    from proto.RSetup import robjects

    rPlot = robjects.r.plot
    rPlot(xData,
          yData,
          type=plotType,
          xlim=robjects.FloatVector(xLim),
          ylim=robjects.FloatVector(yLim),
          main=mainTitle,
          xlab=xTitle,
          ylab=yTitle)
Example #4
0
    def _customRExecution(self, resDictKey, xlab, main):
        from proto.RSetup import r, robjects
        
        xList, yList, xLabel, yLabel = self._getRawData(resDictKey)
        xVec = robjects.FloatVector(xList)
        yVec = robjects.FloatVector(yList)

        rCode = 'plotFunc <- function(xVec, yVec, xlab, ylab, main) {plot(xVec, yVec, type="l", xlab=xlab, ylab=ylab, main=main)}'
        
        #print (xs, ys, xlab, main)
        #print 'rawData: ',self._getRawData(resDictKey)
        r(rCode)(xVec, yVec, xLabel, yLabel, main)
        
        self._plotResultObject = r('dataFunc <- function(xVec, yVec) {list("x"=xVec, "y"=yVec)}')(xVec, yVec)
    def _compute(self):
        tv = self._children[0].getResult()
        # print tv.genomeAnchor.chr
        points = self._children[0].getResult().startsAsNumpyArray()
        binSize = self._children[1].getResult()
        globalPointCount = self._children[2].getResult()

        rCode = '''
k<-function(x,r,a,b,n) {
 if (min(x)<a || max(x)>b) stop("Points must be in interval [a,b]!")
 dmat<-as.matrix(dist(x)) ## calculate distanced between all pairs of points
 diag(dmat)<-Inf ## distance of point to itself (zero) should not be counted, so set this to infinite (i.e., never less than r)
 wmat<-outer(x,x,function(x,y) (pmin(b,pmax(x+abs(x-y),a))-pmin(b,pmax(x-abs(x-y),a)))/(2*abs(x-y))) ## calculate edge correction weights
 iwmat<-1/wmat ## inverse of edge correction weights
 diag(iwmat)<-0 ##  distance of point to itself (zero) should not be counted, so set this to zero (i.e., drops out of sum
 k<-sum(iwmat*(dmat<r))/n^2 ## final K-function: (sum of inverse weights iw_ij where d_ij<r)/n^2
 k/(2*r)
}
'''
        if len(points) == 0:
            #import numpy
            #return numpy.nan
            return None
        else:
            from proto.RSetup import r, robjects
            return r(rCode)(robjects.FloatVector(points), self._bpWindow, 0,
                            binSize, globalPointCount)
Example #6
0
 def _customRExecution(self, resDictKey, xlab, main):
     from proto.RSetup import r, robjects
     #rCode = 'ourHist <- function(ourList, xlab, main, numBins) {vec <- unlist(ourList); hist(vec, col="blue", breaks=numBins, xlab=xlab, main=main)}'
     rCode = \
         '''ourHist <- function(vec, xlab, main, numBins)
            {main = paste(strwrap(main, width=60), collapse="\n");
             hist(vec, col="blue", breaks=numBins, xlab=xlab, main=main)}'''
     #print (self._results.getAllValuesForResDictKey(resDictKey), xlab, main)
     rawData = robjects.FloatVector(self._getRawData(resDictKey))
     #rawData = [float(x) for x in self._getRawData(resDictKey)]
     numBins = max(10, self._getDataPointCount(resDictKey)/5)
     
     '''
     import numpy
     data = numpy.bincount(self._getRawData(resDictKey))
     import quick.webtools.restricted.visualization.visualizationPlots as vp
     from proto.hyperbrowser.HtmlCore import HtmlCore
     self.__class__.numCount +=1
     if self.__class__.numCount==1:
         htmlCore = HtmlCore()
         htmlCore.begin()
         htmlCore.divBegin('plotDiv')
         htmlCore.line(vp.addJSlibs())
         htmlCore.line(vp.useThemePlot())
         htmlCore.line(vp.addJSlibsExport())
         htmlCore.line(vp.axaddJSlibsOverMouseAxisisPopup())
         seriesType = ['column' for x in list(data)]
         
         #linear scale
         """  
         htmlCore.line(vp.drawChart(list(data),
                                    tickInterval=None,
                                    type='column',
                                    label='x= {point.x} </br> y= {point.y}',
                                    seriesType=seriesType,
                                    height=400,
                                    titleText='Histogram',
                                    tickMinValue=1,
                                    legend=False,
                                    plotNumber=self.__class__.numCount
                                    ))
         """
         #log scale
         htmlCore.line(vp.drawChart(list(data),
                                    tickInterval=None,
                                    type='column',
                                    label='x= {point.x} </br> y= {point.y}',
                                    seriesType=seriesType,
                                    height=400,
                                    titleText='Histogram',
                                    typeAxisXScale = 'logarithmic',
                                    pointStartLog=1,
                                    legend=False,
                                    plotNumber=self.__class__.numCount
                                    ))    
         htmlCore.divEnd()
         htmlCore.end()
         print str(htmlCore)
         '''
     self._plotResultObject = r(rCode)(rawData, xlab, main, numBins)
Example #7
0
    def countHist(self, newResList):

        poissonListMean = []
        if len(newResList) != 0:

            from proto.RSetup import r, robjects

            newResListLog = []
            for el in newResList:
                if el == 0:
                    newResListLog.append(0)
                else:
                    newResListLog.append(math.log(el, 10))

            # , breaks=ceiling(max(vec)) - floor((min(vec)))
            rCode = 'dataRPois <- function(vec) {' \
                    'hist(vec, prob=T)' \
                    '}'
            dd = robjects.FloatVector(newResListLog)
            dataFromRPois = r(rCode)(dd)

            breaks = list(dataFromRPois.rx2('breaks'))

            try:
                counts = list(dataFromRPois.rx2('density'))
            except:
                counts = [dataFromRPois.rx2('density')]

            for elN in range(0, len(counts)):
                br = (breaks[elN] + breaks[elN + 1]) / 2
                ct = counts[elN]

                poissonListMean.append([br, ct])

        return poissonListMean
    def execute(cls, choices, galaxyFn=None, username=''):
        '''Is called when execute-button is pushed by web-user.
        Should print output as HTML to standard out, which will be directed to a results page in Galaxy history.
        If getOutputFormat is anything else than HTML, the output should be written to the file with path galaxyFn.
        If needed, StaticFile can be used to get a path where additional files can be put (e.g. generated image files).
        choices is a list of selections made by web-user in each options box.
        '''
        from time import time
        startTime = time()
        from quick.application.ExternalTrackManager import ExternalTrackManager
        from proto.hyperbrowser.StaticFile import GalaxyRunSpecificFile

        motifFn = ExternalTrackManager.extractFnFromGalaxyTN(
            choices[0].split(':'))
        observedFasta = ExternalTrackManager.extractFnFromGalaxyTN(
            choices[1].split(':'))

        randomGalaxyTN = choices[2].split(':')
        randomName = ExternalTrackManager.extractNameFromHistoryTN(
            randomGalaxyTN)
        randomGalaxyFn = ExternalTrackManager.extractFnFromGalaxyTN(
            randomGalaxyTN)
        randomStatic = GalaxyRunSpecificFile(
            ['random'], randomGalaxyFn
        )  #finds path to static file created for a previous history element (randomFn), and directs to a folder containing several files..
        #print os.listdir(randomStatic.getDiskPath())
        randomFastaPath = randomStatic.getDiskPath()

        #motifFn, observedFasta, randomFastaPath = '/Users/sandve/egne_dokumenter/_faglig/NullModels/DnaSeqExample/liver.pwm', 'liver.fa', 'randomFastas'
        testStatistic = choices[3]
        if testStatistic == 'Average of max score per sequence':
            scoreFunc = scoreMotifOnFastaAsAvgOfBestScores
        elif testStatistic == 'Sum of scores across all positions of all sequences':
            scoreFunc = scoreMotifOnFastaAsSumOfAllScores
        elif testStatistic == 'Score of Frith et al. (2004)':
            scoreFunc = lr4
        elif testStatistic == 'Product of max per sequence':
            scoreFunc = scoreMotifOnFastaAsProductOfBestScores
        else:
            raise

        pvals = mcPvalFromMotifAndFastas(motifFn, observedFasta,
                                         randomFastaPath, scoreFunc)
        print 'Pvals for motifs (%s) against observed (%s) vs random (%s - %s) sequences.' % (
            motifFn, observedFasta, randomName, randomFastaPath)
        for motif, pval in sorted(pvals.items()):
            print motif + '\t' + ('%.4f' % pval)

        from proto.hyperbrowser.StaticFile import GalaxyRunSpecificFile
        from proto.RSetup import robjects
        histStaticFile = GalaxyRunSpecificFile(['pvalHist.png'], galaxyFn)
        #histStaticFile.openRFigure()
        histStaticFile.plotRHist(pvals.values(), [x / 40.0 for x in range(41)],
                                 'Histogram of p-values',
                                 xlim=robjects.FloatVector([0.0, 1.0]))
        #r.hist(robjects.FloatVector(pvals.values()), breaks=robjects.FloatVector([x/40.0 for x in range(41)]), xlim=robjects.FloatVector([0.0, 1.0]), main='Histogram of p-values' )
        #histStaticFile.closeRFigure()
        print histStaticFile.getLink('Histogram')
        print 'Time (s):', time() - startTime
 def _compute(self):
     from proto.RSetup import r, robjects
     summaryStats = robjects.FloatVector([
         self._children[0].getResult()[key]
         for key in ['Neither', 'Only1', 'Only2', 'Both']
     ])
     r('library("polycor")')
     tetraCor = r('function(vec){polychor(matrix(vec, nrow=2))}')
     return tetraCor(summaryStats)
Example #10
0
    def _customRExecution(self, resDictKey, xlab, main):
        from proto.RSetup import r, robjects

        xs, ys = self._getRawData(resDictKey)
        xVec = robjects.FloatVector(xs)
        yVec = robjects.FloatVector(ys)

        rCode = 'plotFunc <- function(xVec, yVec, xlab, ylab, main) {plot(xVec, yVec, xlab=xlab, ylab=ylab, main=main); lines(lowess(xVec, yVec),col="red")}'

        #print (xs, ys, xlab, main)
        #print 'rawData: ',self._getRawData(resDictKey)
        xlab = 'Stat-values on track1'  #rename x-lab for scatter-plot case..
        ylab = 'Stat-values on track2'
        r(rCode)(xVec, yVec, xlab, ylab, main)

        self._plotResultObject = r(
            'dataFunc <- function(xVec, yVec) {list("x"=xVec, "y"=yVec)}')(
                xVec, yVec)
def drawBarplot(data, mainTitle, xTitle, yTitle, names, col):
    from proto.RSetup import robjects

    barplot = robjects.r.barplot
    barplot(robjects.FloatVector(data),
            main=mainTitle,
            xlab=xTitle,
            ylab=yTitle,
            names=names,
            col=col)
Example #12
0
    def plotRHist(self,
                  vals,
                  breaks,
                  main,
                  saveRawData=True,
                  alsoOpenAndClose=True,
                  **kwArgs):
        from proto.RSetup import r, robjects
        rvals = robjects.FloatVector(vals)
        if type(breaks) in [list, tuple]:
            rbreaks = robjects.FloatVector(breaks)
        else:
            rbreaks = breaks
        if not 'xlab' in kwArgs:
            kwArgs['xlab'] = 'Values'

        if alsoOpenAndClose:
            self.openRFigure()

        histRes = r.hist(rvals, breaks=rbreaks, main=main, **kwArgs)

        if saveRawData:
            rawFn = self.getDiskPath() + '.raw.txt'
            f = open(rawFn, 'w')
            f.write('vals <- c(%s)' % ','.join(str(val)
                                               for val in vals) + '\n')
            if type(breaks) in [list, tuple]:
                f.write('breaks <- c(%s)' % ','.join(str(b)
                                                     for b in breaks) + '\n')
            else:
                f.write('breaks <- %s' % breaks)
            f.write('hist(vals, breaks=breaks) \n')
            #r('prn=print')
            intensities = r('function(r){r$intensities}')(histRes)
            f.write('intensities = c(%s)' %
                    ','.join([str(x) for x in intensities]) + '\n')
            f.close()

        if alsoOpenAndClose:
            self.closeRFigure()
Example #13
0
    def _compute(self):
        #try:
        track = [None, None]
        for i in [0, 1]:
            tv = self._children[i].getResult()
            track[i] = []
            for index, el in enumerate(tv):
                if el.start() == el.end() == None:
                    track[i] += [index, index + 1, float(el.val())]
                else:
                    track[i] += [
                        int(el.start()),
                        int(el.end()),
                        int(float(el.val())) if el.val() is not None else nan
                    ]

        #print "track 0 before unlist: " %, track[0]
        #print "track 1 before unlist: " % track[1]
        header = [
            'rCompute <- function(track1, track2) {',
            #'track1[unlist(sapply(track1,is.null))] <- NA',
            #'track2[unlist(sapply(track2,is.null))] <- NA',
            #'track1 <- unlist(track1)',
            #'track2 <- unlist(track2)',
            'dim(track1) <- c(3,' + str(len(track[0]) / 3) + ')',
            'dim(track2) <- c(3,' + str(len(track[1]) / 3) + ')',
            'result <- 0'
        ]
        footer = ['return(result)', '}']
        allLines = header + self._codeLines + footer

        from proto.RSetup import r, robjects

        track[0] = robjects.FloatVector(track[0])
        #print "track 0 after unlist: ", track[0]
        track[1] = robjects.FloatVector(track[1])
        #print "track 1 after unlist: ", track[1]

        return r('\n'.join(allLines))(track[0], track[1])
def drawVioplot(plotDataMatrix, xlabels, mainTitle, xTitle, yTitle,
                vioplotColor, xAxisAt, xLimMin, xLimMax, xLas, yAxisAt,
                yLimMin, yLimMax, yLas):
    from proto.RSetup import robjects

    convertedData = [robjects.FloatVector(x) for x in plotDataMatrix]
    rplot = robjects.r.plot
    axis = robjects.r.axis
    from rpy2.robjects.packages import importr
    vioplot = importr("vioplot")
    rplot([1], [1],
          type='n',
          xlim=robjects.FloatVector([xLimMin, xLimMax]),
          ylim=robjects.FloatVector([yLimMin, yLimMax]),
          axes=False,
          ann=False)
    vioplot.vioplot(col=vioplotColor, add=True, *convertedData)
    axis(1, at=xAxisAt, labels=xlabels, las=xLas)
    axis(2, at=yAxisAt, las=yLas)
    title = robjects.r.title
    title(main=mainTitle)
    title(xlab=xTitle)
    title(ylab=yTitle)
def drawHeatmap(heatmapPlotData, rowLabels, colLabels, mainTitle, symm=True):
    """heatmapPlotData is a matrix represented by a list of lists"""
    from proto.RSetup import robjects

    from numpy import matrix
    heatmap = robjects.r.heatmap
    rmatrix = robjects.r.matrix
    flatData = matrix(heatmapPlotData).flatten().tolist()[0]
    data = robjects.FloatVector(flatData)
    heatmap(rmatrix(data, nrow=len(rowLabels)),
            labRow=rowLabels,
            labCol=colLabels,
            main=mainTitle,
            symm=symm)
    def _compute(self):
        from proto.RSetup import robjects, r
        #if self._minimal:
        #    return {'Result': OrderedDict([('Matrix', np.array([], dtype='float64')), \
        #                                   ('Rows', np.array([], dtype='S1')), \
        #                                   ('Cols', np.array([], dtype='S1'))])}
        #
        #rawData = self._children[0].getResult()
        #edges = rawData.edgesAsNumpyArray()
        #weights = rawData.weightsAsNumpyArray()
        #ids = rawData.idsAsNumpyArray()
        #
        #if len(edges) > 0:
        #    assert all((x==edges[0]).all() for x in edges), 'Edge arrays are not equal for all elements'
        #
        #x,y = weights.shape
        #assert x == y, 'Weight matrix is not square, %s != %s' % (x,y)

        graph = self._graphStat.getResult()
        res = graph.getEdgeWeightMatrixRepresentation(completeMatrix=self._complete, \
                                                      rowsAsFromNodes=self._rowsAsFromNodes, \
                                                      missingEdgeWeight=np.nan)

        if self._normalizationMethod != 'none':
            if self._normalizationMethod == 'log':
                res['Matrix'] = np.log(res['Matrix'])
            if self._normalizationMethod == 'log+1':
                res['Matrix'] = np.log(res['Matrix'] + 1)
            elif self._normalizationMethod == 'p_inverse':
                res['Matrix'] = 1 - res['Matrix']
            else:
                origShape = res['Matrix'].shape
                if self._normalizationMethod == 'p_to_normal_onesided':
                    intermed = 1 - res['Matrix']
                else:  #p_to_normal_twosided
                    intermed = 1 - res['Matrix'] / 2
                vec = robjects.FloatVector(intermed.flatten())
                # To remove -Inf anf Inf values
                vec = r(
                    'f <- function(vec){vec[vec==0] = .Machine$double.eps; vec[vec==1] = 1-.Machine$double.eps;vec}'
                )(vec)
                res['Matrix'] = np.array(list(r.qnorm(vec)))
                res['Matrix'].shape = origShape

        return {'Result': res}
    def getLinkToLocalResultsHeatmap(self, linkText, disease, resDictKey,
                                     galaxyFn):
        values = []
        allLocalResults = self.getAllLocalResults(resDictKey,
                                                  fillInNoneValues=True)
        allLocalRegions = self.getLocalRegions()
        refSubTypes = self.getRefSubTypes()
        numRows = len(allLocalRegions)
        for localRegion in allLocalRegions:
            for refSubType in refSubTypes:
                values.append(allLocalResults[refSubType][localRegion])

        if None in values or any(numpy.isnan(x) for x in values):
            return 'Not generated, due to missing values'
        #if not ( 0 < (float(sum(values)) / len(values)) < 100000):
        #    return 'Not generated, due to too small/large values (average: %s)' % (float(sum(values)) / len(values))
        maxVal = max(values)
        from proto.RSetup import r, robjects
        r('library(gplots)')
        dataMatrix = r.matrix(robjects.FloatVector(values), nrow=numRows)
        if (r.length(r.unique(r.colSums(dataMatrix))) <= 1) or (r.length(
                r.unique(r.rowSums(dataMatrix))) <= 1):
            return 'Not generated, due to lacking variation'
        dataMatrix = r('function(data,names){rownames(data)=names; data}')(
            dataMatrix, [str(x) for x in allLocalRegions])
        dataMatrix = r('function(data,names){colnames(data)=names; data}')(
            dataMatrix, refSubTypes)
        #print 'dimensions dataMatrix: ', r.dim(dataMatrix), dataMatrix
        sf = GalaxyRunSpecificFile(
            ['LocalResultTables', resDictKey, disease + '_heatmap.png'],
            galaxyFn)
        sf.openRFigure(h=4000, w=4000)
        r("function(data,maxVal){heatmap.2(data,col =c('#99FFFF',colorRampPalette(c('cyan','blue', 'black', 'red', 'yellow'))(161),'#FFFF66'), breaks = seq(0,maxVal,length=164),trace='none',margins=c(15,15))}"
          )(dataMatrix, maxVal)
        #r("function(data){heatmap(data)}")(dataMatrix)
        sf.closeRFigure()
        return sf.getLink(linkText)
def drawMultiHistogram(data,
                       mainTitle,
                       xTitle,
                       yTitle,
                       names=None,
                       colors=None,
                       hasLegend=False):
    from proto.RSetup import robjects

    from rpy2.robjects.packages import importr
    plotrix = importr('plotrix')
    multhist = plotrix.multhist

    legend = robjects.r.legend

    plotData = [robjects.FloatVector(x) for x in data]
    multhist(plotData,
             col=colors,
             main=mainTitle,
             beside=True,
             xlab=xTitle,
             ylab=yTitle)
    if hasLegend:
        legend('topleft', legend=names, pch=15, col=colors, bty='n')
Example #19
0
    def countPoissonDistribution(self, numMut, intervalLen):

        poissonListMean = []

        if numMut != 0:

            from proto.RSetup import r, robjects
            # number of mutation/ length of interval
            rCode = 'dataRPois <- function(vec) {' \
                    'vecNew = log10(rexp(10000, vec[1]/vec[2])); ' \
                    'data=hist(vecNew, prob=T)' \
                    '}'
            dd = robjects.FloatVector(
                [numMut, intervalLen])
            dataFromRPois = r(rCode)(dd)

            breaks = list(dataFromRPois.rx2('breaks'))
            counts = list(dataFromRPois.rx2('density'))
            for elN in range(0, len(counts)):
                br = (breaks[elN] + breaks[elN + 1]) / 2
                ct = counts[elN]
                poissonListMean.append([br, ct])

        return poissonListMean
 def _combineResults(self):
     from proto.RSetup import robjects, r
     rVec1 = robjects.FloatVector([x[0] for x in self._childResults])
     rVec2 = robjects.FloatVector([x[1] for x in self._childResults])
     return r.cor(rVec1, rVec2, method=self._corrMethod)
Example #21
0
    def _customRExecution(self, resDictKey, xlab, main):
        from proto.RSetup import r, robjects

        rCode = ('ourHeatmap <- function(matrix, rowNames, colNames, rowClust,'
                 'colClust, dendrogram, marginLeft, '
                 'marginTop, mapHeight, mapWidth, '
                 'margins, cex, font, col, breaks, cellnote){'
                 'dimnames(matrix) <- list(rowNames, colNames); '
                 'sink(file("/dev/null", open="wt"), type="output"); '
                 'library(gplots); sink(); options(expressions=100000); '
                 'if (typeof(rowClust) != "logical") {'
                 'class(rowClust) = "hclust"; '
                 'rowClust = as.dendrogram(rowClust)}; '
                 'if (typeof(colClust) != "logical") {'
                 'class(colClust) = "hclust"; '
                 'colClust = as.dendrogram(colClust)}; '
                 'dim(cellnote) = rev(dim(matrix)); '
                 'cellnote = t(cellnote); '
                 'return(heatmap.2(matrix, trace="none", Rowv=rowClust, '
                 'Colv=colClust, dendrogram=dendrogram, '
                 'margins=margins, na.rm=TRUE, '
                 'na.color="white", col=col, breaks=breaks, '
                 'lhei=c(marginTop,mapHeight), '
                 'lwid=c(marginLeft,mapWidth), '
                 'cexRow=cex, cexCol=cex, font=font, '
                 'key=(min(marginTop, marginLeft) >= 150), '
                 'keysize=1, cellnote=cellnote, '
                 'notecex=2, notecol="black"))}')

        tableData = self._getRawData(resDictKey)

        assert isinstance(tableData, TableData)
        matrix = tableData.numpyMatrix
        rowNames = tableData.rowNamesAsNumpyArray
        colNames = tableData.columnNamesAsNumpyArray
        significance = tableData.significanceMatrix
        rowClust = tableData.rowClust
        colClust = tableData.colClust

        rowClust, colClust = [
            x if x is not None else False for x in [rowClust, colClust]
        ]
        dendrogram = [["both", "row"],
                      ["column", "none"]][rowClust == False][colClust == False]

        hist = numpy.histogram(
            matrix, bins=[-numpy.Inf, -1 - 1e-9, 0, 1 + 1e-9, numpy.Inf])[0]
        if hist[0] + hist[1] + hist[3] == 0:  #Only counts between 0 and 1
            col = r("colorRampPalette(c('black', 'red', 'yellow'))")
            breaks = 82
        elif hist[0] + hist[3] == 0:  #Only counts between -1 and 1
            col = r(
                "colorRampPalette(c('cyan', 'blue', 'black', 'red', 'yellow'))"
            )
            breaks = 164
        #elif hist[0] == 0: #Assume unbalanced score, most values between -1 and 0
        #    col = r("colorRampPalette(c('blue', 'black', 'red', 'yellow'))")
        #    matmax = matrix.max()
        #    breaks = r("function(matmax) {c(seq(-1.02,0.98,length=51), seq(1.02,matmax,length=26))}")(matmax)
        elif hist[0] == 0:  #Only positive counts
            col = r("colorRampPalette(c('black', 'red', 'yellow'))")
            breaks = 164
        else:  #Assumes normal distribution
            col = r(
                "c('#99FFFF',colorRampPalette(c('cyan','blue', 'black', 'red', 'yellow'))(161),'#FFFF66')"
            )
            breaks = r("seq(-4.075,4.075,length=164)")


#        if numpy.argmax(hist) == 1: #Adjust color palette
#            matmax = matrix.max()
#            matmin = matrix.min()
#            if matmin < -1.0:
#                breaks = numpy.arange(matmin,-1.0,(-1.0-matmin)/20)
#                withBlack = True
#            else:
#                breaks = numpy.array([])
#                withBlack = False
#            breaks = numpy.concatenate((breaks, \
#                                       numpy.arange(-1,1,1.0/20)))
#            if matmax > 1.0:
#                breaks = numpy.concatenate((breaks, \
#                                           numpy.arange(1, matmax, (matmax-1.0)/20), \
#                                           numpy.array([matmax])))
#                withWhite = True
#            else:
#                breaks = numpy.concatenate((breaks, \
#                                           numpy.array([1.0])))
#                withWhite = False
#            rFunc = '''
#function(numCols, withBlack, withWhite) {
#    cols = c("red","orange","yellow")
#    if(withBlack) {
#        cols = c("black", cols)
#    }
#    if(withWhite) {
#        cols = c(cols, "white")
#    }
#    colorRampPalette(cols)(numCols)
#}'''
#            col = r(rFunc)(len(breaks)-1, withBlack, withWhite)
#else:
#            col = 'heat.colors'
#            breaks = 80

        cellnote = numpy.zeros(shape=matrix.shape, dtype='S1')
        if significance is not None:
            cellnote[significance] = 'o'

        self._returnDict[resDictKey] = \
            r(rCode)(matrix, [x for x in rowNames], [x for x in colNames], rowClust, colClust, dendrogram, \
                     self._marginLeft, self._marginTop, self._mapHeight, self._mapWidth, \
                     robjects.FloatVector(self._getMarginsInLineHeights()), \
                     self._cex, self.FONT, col, breaks, cellnote.flatten().tolist())