def _writeContent(self, fn, header, resDictKey, coreCls):
        keys = self._getKeys(resDictKey)

        core = coreCls()
        
        core.begin()
        core.bigHeader(header)
        core.header('Local result table for ' + resDictKey)
        
        if len( self._results.getAllRegionKeys() ) > MAX_LOCAL_RESULTS_IN_TABLE:
            core.line('Local results were not printed because of the large number of bins: ' \
                  + str(numUserBins) + ' > ' + str(MAX_LOCAL_RESULTS_IN_TABLE))
        else:
            core.tableHeader([ str( coreCls().textWithHelp(baseText, helpText) ) for baseText, helpText in 
                              ([('Region','')] + [self._results.getLabelHelpPair(key) for key in keys]) ])
            
            for regionKey in self._results.getAllRegionKeys():
                if  self._results[regionKey].get(resDictKey) is None:
                    core.tableLine([str(regionKey)] + [None]*len(keys))
                else:
                    core.tableLine([str(regionKey)] +\
                                   [ strWithStdFormatting( self._results[regionKey][resDictKey].get(key) ) for key in keys])
            core.tableFooter()

        core.end()
        
        ensurePathExists(fn)        
        open(fn,'w').write( str(core) )
Пример #2
0
    def _writeContent(self, fn, header, resDictKey, coreCls):
        keys = self._getKeys(resDictKey)

        core = coreCls()

        core.begin()
        core.bigHeader(header)
        core.header('Local result table for ' + resDictKey)

        if len(self._results.getAllRegionKeys()) > MAX_LOCAL_RESULTS_IN_TABLE:
            core.line('Local results were not printed because of the large number of bins: ' \
                  + str(numUserBins) + ' > ' + str(MAX_LOCAL_RESULTS_IN_TABLE))
        else:
            core.tableHeader([
                str(coreCls().textWithHelp(baseText, helpText))
                for baseText, helpText in (
                    [('Region', '')] +
                    [self._results.getLabelHelpPair(key) for key in keys])
            ])

            for regionKey in self._results.getAllRegionKeys():
                if self._results[regionKey].get(resDictKey) is None:
                    core.tableLine([str(regionKey)] + [None] * len(keys))
                else:
                    core.tableLine([str(regionKey)] +\
                                   [ strWithStdFormatting( self._results[regionKey][resDictKey].get(key) ) for key in keys])
            core.tableFooter()

        core.end()

        ensurePathExists(fn)
        open(fn, 'w').write(str(core))
    def allInfo(self, printEmpty=False):
        core = HtmlCore()
        isDense = self._isDenseTrack()

        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'subTrackCount', \
            self.subTrackCount and (self.subTrackCount > 1 or not self.isValid()))
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'origElCount', self.origElCount, \
            lambda x: strWithStdFormatting(x))
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'clusteredElCount', self.clusteredElCount, \
            lambda x: strWithStdFormatting(x))
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'numValCategories', self.numValCategories, \
            lambda x: strWithStdFormatting(x))
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'numClusteredValCategories', self.numClusteredValCategories, \
            lambda x: strWithStdFormatting(x))
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'numEdgeWeightCategories', self.numEdgeWeightCategories, \
            lambda x: strWithStdFormatting(x))

        self._addTrackTypeIllustration(core, self.trackFormatName)

        return self.mainInfo(printEmpty) + unicode(core)
Пример #4
0
    def allInfo(self, printEmpty=False):
        core = HtmlCore()
        isDense = self._isDenseTrack()
        
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'subTrackCount', \
            self.subTrackCount and (self.subTrackCount > 1 or not self.isValid()))
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'origElCount', self.origElCount, \
            lambda x: strWithStdFormatting(x))
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'clusteredElCount', self.clusteredElCount, \
            lambda x: strWithStdFormatting(x))
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'numValCategories', self.numValCategories, \
            lambda x: strWithStdFormatting(x))
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'numClusteredValCategories', self.numClusteredValCategories, \
            lambda x: strWithStdFormatting(x))
        self._addDescriptionLineIfTrue(core, isDense, printEmpty, 'numEdgeWeightCategories', self.numEdgeWeightCategories, \
            lambda x: strWithStdFormatting(x))
        
        self._addTrackTypeIllustration(core, self.trackFormatName)

        return self.mainInfo(printEmpty) + unicode(core)
Пример #5
0
    def allInfo(self, printEmpty=False):
        core = HtmlCore()

        if printEmpty or self.assemblyDetails:
            core.descriptionLine('Assembly details', self.assemblyDetails)

        if printEmpty or hasattr(self, 'numChrs') and self.numChrs:
            if hasattr(self, 'numExtChrs') and self.numExtChrs > 0:
                core.descriptionLine('Number of standard chromosomes',
                                     strWithStdFormatting(self.numChrs))
            else:
                core.descriptionLine('Number of chromosomes',
                                     strWithStdFormatting(self.numChrs))

        if printEmpty or hasattr(self, 'numExtChrs') and self.numExtChrs:
            core.descriptionLine('Number of extended chromosomes',
                                 strWithStdFormatting(self.numExtChrs))

        if printEmpty or hasattr(self, 'numBps') and self.numBps:
            if hasattr(self, 'numExtChrs') and self.numExtChrs > 0:
                core.descriptionLine(
                    'Total number of bps (standard chromosomes only)',
                    strWithStdFormatting(self.numBps))
            else:
                core.descriptionLine('Total number of bps',
                                     strWithStdFormatting(self.numBps))

        if printEmpty or hasattr(self, 'numBpsWithExt') and hasattr(
                self, 'numExtChrs') and self.numBpsWithExt and self.numExtChrs:
            core.descriptionLine(
                'Total number of bps (with extended chromosomes)',
                strWithStdFormatting(self.numBpsWithExt))

        return self.mainInfo(printEmpty) + str(core)
Пример #6
0
    def getReference(self, resDictKey):
        globalRes = self._results.getGlobalResult()
        htmlObj = GalaxyRunSpecificFile(['test.html'], self._baseDir)
        fileObj = open(htmlObj.getDiskPath(ensurePath=True), 'w')
        #fileObj.write( 'globalRes ' + str(globalRes))
        htmlText = CreateBpsVennDIagram.getHtmlString(
            globalRes['result']['catInfo'],
            globalRes['result']['stateBPCounter'],
            globalRes['result']['genome'])
        fileObj.write(htmlText)
        fileObj.close()

        return htmlObj.getLink('link to results')
        return str(globalRes)
        return strWithStdFormatting(
            globalRes[resDictKey]) if globalRes not in [None, {}] else 'None'
    def _writeContent(self, fn, resDictKey, header, coreCls):
        ensurePathExists(fn)
        outFile = open(fn,'w')

        core = coreCls()
        core.begin()
        core.bigHeader(header)
        core.header(self.HEADER)

        matrixDict = self._getRawData(resDictKey)
        matrix, rownames, colnames, rowOrder, colOrder = [copy(matrixDict.get(x)) for x in \
                                                          [self.MATRIX_VALUE_KEY,'Rows','Cols', 'RowOrder', 'ColOrder']]
#        matrix, rownames, colnames, rowOrder, colOrder = [matrixDict.get(x) for x in \
#                                                          [self.MATRIX_VALUE_KEY,'Rows','Cols', 'RowOrder', 'ColOrder']]
        
#        print matrix, rownames, colnames, rowOrder, colOrder
    
        if matrix is None:
            raise SilentError
    
        if rowOrder is not None:
            rownames = rownames[rowOrder]
            matrix = matrix[rowOrder]

        if colOrder is not None:
            colnames = colnames[colOrder]
            matrix = matrix[:,colOrder]

        core.tableHeader([''] + [ str( coreCls().textWithHelp(baseText, helpText) ) for baseText, helpText in \
                          [self._results.getLabelHelpPair(col) for col in colnames] ], sortable=True)
        for i,row in enumerate(matrix):
            core.tableLine([ str( coreCls().textWithHelp(*self._results.getLabelHelpPair(rownames[i])) ) ] +\
                           [ strWithStdFormatting( row[i] ) for i in xrange(len(row)) ])
            # In order for the memory usage and handling time not to explode for large tables
            outFile.write( str(core) )
            core = coreCls()
        core.tableFooter()

        core.end()
        outFile.write( str(core) )
        outFile.close()
    def _writeContent(self, fn, header):
        #core = HtmlCore()

        #core.begin()
        #core.bigHeader(header)
        #core.header('Local result table')
        text = ''
        if len(self._results.getAllRegionKeys()) > MAX_LOCAL_RESULTS_IN_TABLE:
            text += 'Local results were not printed because of the large number of bins: ' \
                  + str(numUserBins) + ' > ' + str(MAX_LOCAL_RESULTS_IN_TABLE)
        else:
            #core.tableHeader([ str( HtmlCore().textWithHelp(baseText, helpText) ) for baseText, helpText in
            #                  ([('Region','')] + self._results.getLabelHelpPairs()) ])

            for regionKey in self._results.getAllRegionKeys():
                text += '\t'.join([str(regionKey)] +\
                    [ strWithStdFormatting( self._results[regionKey].get(resDictKey) ) \
                     for resDictKey in self._results.getResDictKeys() ]) + os.linesep
            #core.tableFooter()

        #core.end()

        ensurePathExists(fn)
        open(fn, 'w').write(text)
    def _writeContent(self, fn, header):
        #core = HtmlCore()
        
        #core.begin()
        #core.bigHeader(header)
        #core.header('Local result table')
        text = ''
        if len( self._results.getAllRegionKeys() ) > MAX_LOCAL_RESULTS_IN_TABLE:
            text += 'Local results were not printed because of the large number of bins: ' \
                  + str(numUserBins) + ' > ' + str(MAX_LOCAL_RESULTS_IN_TABLE)
        else:
            #core.tableHeader([ str( HtmlCore().textWithHelp(baseText, helpText) ) for baseText, helpText in 
            #                  ([('Region','')] + self._results.getLabelHelpPairs()) ])
            
            for regionKey in self._results.getAllRegionKeys():
                text += '\t'.join([str(regionKey)] +\
                    [ strWithStdFormatting( self._results[regionKey].get(resDictKey) ) \
                     for resDictKey in self._results.getResDictKeys() ]) + os.linesep
            #core.tableFooter()

        #core.end()
        
        ensurePathExists(fn)        
        open(fn,'w').write( text )
 def getReference(self, resDictKey):
     globalRes = self._results.getGlobalResult()
     return strWithStdFormatting( globalRes[resDictKey] ) if globalRes not in [None,{}] else 'None'
Пример #11
0
 def format(self, val):
     from gold.util.CommonFunctions import strWithStdFormatting
     self._str += strWithStdFormatting(val, separateThousands=False)
     return self
Пример #12
0
 def getReference(self, resDictKey):
     globalRes = self._results.getGlobalResult()
     return strWithStdFormatting(
         globalRes[resDictKey]) if globalRes not in [None, {}] else 'None'
Пример #13
0
    def _generateAnswerText(self, coreCls):
        onlyLocalPvals = self._results.hasOnlyLocalPvals()
        globalPval = self._results.getGlobalResult().get(
            self._results.getPvalKey()) if not onlyLocalPvals else None

        tableFile = GalaxyRunSpecificFile(['table.html'], galaxyFn='')
        localPvalsUrl = tableFile.getURL(
        )  #problematic dependency towards fn in tablePresenter..

        core = coreCls()
        core.styleInfoBegin(styleClass="infomessagesmall answerbox question")
        core.header('You asked:')
        core.line(str(coreCls().highlight(self._getHeader())))
        core.styleInfoEnd()

        #Simplistic answer
        core.styleInfoBegin(
            styleClass="infomessagesmall answerbox simplisticanswer")
        core.header(str(coreCls().link('Simplistic answer:', '#', \
                                        args='''onclick="return toggle('simplistic_answer_expl')"''')))

        core.styleInfoBegin(styleId="simplistic_answer_expl",
                            styleClass="infomessagesmall explanation")
        if onlyLocalPvals:
            core.line('''
Under "simplistic answer" you will find a simple statement on whether there were any findings for the local analysis. The number of significant bins at 10% false discovery rate (FDR) is provided.<br>
<br>
It is not possible to draw a decisive conclusion based on a p-value, so the statements are only meant as simple indications.<br>
                  ''')
        else:
            core.line('''
Under "simplistic answer" you will find a yes/maybe/no-conclusion answer to the question asked, based on a simple thresholding scheme on the p-value:<br>
"yes" if p-value < 0.01<br>
"maybe" if  0.01 < p-value < 0.1<br>
"no conclusion" if p-value > 0.1<br>
<br>
It is not possible to draw a decisive conclusion based on a p-value, so the statements are only meant as simple indications.<br>                  
                  ''')

        core.styleInfoEnd()

        if onlyLocalPvals:
            numSign, numTested, numIgnored = self._results.getFdrSignBins()
            if numSign == numTested and numSign != 0:
                simplisticPhrase = 'Yes - the data suggests this for all bins'
            elif numSign > 0:
                simplisticPhrase = 'Yes - the data suggests this at least in some bins'
                numSign, numTested, numIgnored = self._results.getFdrSignBins()
                simplisticPhrase += ' (%i significant bins out of %i, at %i%% FDR)' % (
                    numSign, numTested, self._results.FDR_THRESHOLD * 100)
            else:
                simplisticPhrase = 'No support from data for this conclusion in any bin'

            core.line(str(coreCls().highlight(simplisticPhrase)))
        else:
            assert globalPval is not None

            directionality = ''
            if self._results._isTwoSidedTest:
                tsValue, expTsValue = self._getTestStatisticAndExpectedValues()
                if tsValue is not None and expTsValue is not None and tsValue != expTsValue:
                    directionality = '(higher) ' if tsValue > expTsValue else '(lower) '

            if globalPval < 0.01:
                simplisticPhrase = 'Yes %s- the data suggests this' % directionality
            elif globalPval < 0.1:
                simplisticPhrase = 'Maybe %s- weak evidence' % directionality
            else:
                simplisticPhrase = 'No support from data for this conclusion'

            core.line(
                str(coreCls().highlight(simplisticPhrase + ' (p-value: ' +
                                        strWithStdFormatting(globalPval) +
                                        ')')))
        core.styleInfoEnd()

        #Precise answer
        core.styleInfoBegin(
            styleClass="infomessagesmall answerbox preciseanswer")
        core.header(str(coreCls().link('Precise answer:', '#', \
                                       args='''onclick="return toggle('precise_answer_expl')"''')))

        core.styleInfoBegin(styleId="precise_answer_expl",
                            styleClass="infomessagesmall explanation")
        if onlyLocalPvals:
            core.line('''
Significance testing evaluates a <b>null hypothesis (H0)</b> versus an <b>alternative hypothesis (H1)</b>. Low <b>p-values</b> are evidence against H0. The testing involves comparing the observed value of a  <b>test statistic</b> to the distribution of the test statistic under a <b>null model</b>. The testing was performed in each local bin, with a list of FDR-corrected p-values per bin provided.                  
                  ''')
        else:
            core.line('''
Significance testing evaluates a <b>null hypothesis (H0)</b> versus an <b>alternative hypothesis (H1)</b>. Low <b>p-values</b> are evidence against H0. The testing involves comparing the observed value of a  <b>test statistic</b> to the distribution of the test statistic under a <b>null model</b>. 
                  ''')

        core.styleInfoEnd()

        EffectSizeText = 'Please note that both the effect size and the p-value should be considered in order to assess the practical significance of a result.'

        FDR_text = '* False Discovery Rate: The expected proportion of false positive results among the significant bins is no more than %i%%.' \
                    % (self._results.FDR_THRESHOLD*100)

        if onlyLocalPvals:
            numSign, numTested, numIgnored = self._results.getFdrSignBins()

            core.line(str(coreCls().highlight('%i significant bins out of %i, at %i' \
                                              % (numSign, numTested, self._results.FDR_THRESHOLD*100) + '% FDR*')))
            core.line('')
            localPvalsLink = str(coreCls().link(
                'collection of FDR-corrected p-values per bin', localPvalsUrl))
            notComputeLink = str(coreCls().link('Not able to compute', '#', \
                                               args='''onclick="return toggle('no_global_pval_expl')"'''))
            core.line('A ' + localPvalsLink + ' was computed. ' +
                      notComputeLink + ' a global p-value for this analysis.')
            core.styleInfoBegin(styleId="no_global_pval_expl",
                                styleClass="infomessagesmall explanation")
            core.line('(Explanation to appear in box)')
            core.styleInfoEnd()

            if numIgnored > 0:
                core.line('')
                core.line('%s bin%s excluded due to lack of data.' %
                          (numIgnored, 's' if numIgnored > 1 else ''))

            core.line('')
            core.line(EffectSizeText)
            core.line('')
            core.line(FDR_text)

            h0h1Text = self._getH0andH1Text(coreCls)
            if h0h1Text is not None:
                core.divider(withSpacing=True)
                core.line('In each bin, the test of')
                core.append(h0h1Text)
                core.line('was performed.')
        else:
            h0h1Text = self._getH0andH1Text(coreCls)
            if h0h1Text is not None:
                core.line('The p-value is %s for the test' %
                          strWithStdFormatting(globalPval))
                core.append(h0h1Text)
            else:
                core.line('The p-value is %s.' %
                          strWithStdFormatting(globalPval))
                core.line('')
            core.line('Low p-values are evidence against H0.')

            numSign, numTested, numIgnored = self._results.getFdrSignBins()
            if numTested + numIgnored > 1:
                localPvalsLink = str(coreCls().link('each bin separately',
                                                    localPvalsUrl))
                excludeText = ' (%i bin%s excluded from FDR-analysis due to lacking p-values).' \
                              % (numIgnored, 's' if numIgnored>1 else '.') if numIgnored>0 else ''
                core.line('')
                core.line('The test was also performed for ' + localPvalsLink + \
                          ', resulting in %i significant bins out of %i, at %i%% FDR*' % (numSign, numTested, self._results.FDR_THRESHOLD*100) +\
                          excludeText)

            core.line('')
            core.line(EffectSizeText)
            core.line('')
            core.line(FDR_text)

        nullModel = self._results._nullModel
        if nullModel is not None:
            core.divider(withSpacing=True)
            core.line('P-values were computed under the %s defined by the following preservation and randomization rules:' \
                      % str(coreCls().highlight('null model')))
            core.paragraph(nullModel, indent=True)

        testStatistic = self._results.getTestStatisticText()
        if testStatistic != None:
            #pick out relevant part:
            mo = re.search('^[tT]est.[sS]tatistic ?:? ?', testStatistic)
            if mo != None:
                testStatistic = testStatistic[mo.end():]
                #if len(testStatistic)>0 and testStatistic[0]=='(':
                #testStatistic = testStatistic[1:]
                #if len(testStatistic)>0 and testStatistic[-1]==')':
                #testStatistic = testStatistic[:-1]

            tsValue, expTsValue = self._getTestStatisticAndExpectedValues()
            core.divider(withSpacing=True)
            core.line('The %s used is:' %
                      str(coreCls().highlight('test statistic')))
            core.paragraph(testStatistic, indent=True)

            if tsValue is not None:
                if expTsValue is not None:
                    core.line('The value of the test statistic is %s, which is %s the expected value: %s.' \
                                % (strWithStdFormatting(tsValue), \
                                   (str(coreCls().emphasize('higher')) + ' than' if tsValue > expTsValue else \
                                    (str(coreCls().emphasize('lower')) + ' than' if tsValue < expTsValue else \
                                     str(coreCls().emphasize('equal')) + ' to')), \
                                   strWithStdFormatting(expTsValue)))
                else:
                    core.line('The value of the test statistic is %s.' %
                              (strWithStdFormatting(tsValue)))

        #temporary solution, as lacking objects needed to construct note-link directly..
        noteText = ''
        if self._results._runDescription is not None:
            #mo = re.search('<note.*note>', self._results._runDescription)
            mo = re.search('<a href[^>]*/notes/[^>]*>[^<]*</a>',
                           self._results._runDescription)
            if mo is not None:
                noteLink = mo.string[mo.start():mo.end()]
                noteText = ' See ' + noteLink + ' for a more complete description of the test.'

        if noteText == '':
            logMessage(
                'Note-link not found in runDescription, and thus omitted from results'
            )

        core.divider(withSpacing=True)

        runDescLink = str(coreCls().link('run description', '#', \
                                         args='''onclick="return toggle('run_description')"'''))
        core.line('The p-values may be subject to further parameter choices, which are listed in the %s.' %\
                  (runDescLink) + noteText)
        core.divider(withSpacing=True)
        #resultsLink = str(coreCls().link('See full details', '#', \
        #args='''onclick="return toggle('results_box')"'''))
        resultsLink = str(coreCls().link('See full details', '#', \
                                         args='''onclick="$('.resultsbox').toggle()"'''))
        core.line(resultsLink + ' of the results in table form.')
        core.styleInfoEnd()

        return str(core)
    def execute(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 gold.application.LogSetup import setupDebugModeAndLogging
        #setupDebugModeAndLogging()

#         targetTrackNames, targetTrackCollection, targetTrackGenome = getGSuiteDataFromGalaxyTN(choices.gSuiteFirst)
#         targetTracksDict = OrderedDict(zip(targetTrackNames, targetTrackCollection))
#         refTrackNames, refTrackCollection, refTrackCollectionGenome = getGSuiteDataFromGalaxyTN(choices.gSuiteSecond)
#         refTracksDict = OrderedDict(zip(refTrackNames, refTrackCollection))
#         
        targetGSuite = getGSuiteFromGalaxyTN(choices.gSuiteFirst)
        refGSuite = getGSuiteFromGalaxyTN(choices.gSuiteSecond)

        regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices)


        if choices.intraOverlap == TrackCollectionsAnalysis.MERGE_INTRA_OVERLAPS:
            analysisDef = 'dummy -> RawOverlapStat'
        else:
            analysisDef = 'dummy [withOverlaps=yes] -> RawOverlapAllowSingleTrackOverlapsStat'
        results = OrderedDict()
#         for targetTrackName, targetTrack in targetTracksDict.iteritems():
#             for refTrackName, refTrack in refTracksDict.iteritems():
        for targetTrack in targetGSuite.allTracks():
            targetTrackName = targetTrack.title
            for refTrack in refGSuite.allTracks():
                refTrackName = refTrack.title
                if targetTrack.trackName == refTrack.trackName:
                    result = TrackCollectionsAnalysis.handleSameTrack(targetTrack.trackName, regSpec, binSpec,
                                                       choices.genome, galaxyFn)
                else:
                    result = GalaxyInterface.runManual([targetTrack.trackName, refTrack.trackName],
                                                       analysisDef, regSpec, binSpec,
                                                       choices.genome, galaxyFn,
                                                       printRunDescription=False,
                                                       printResults=False).getGlobalResult()
                if targetTrackName not in results :
                    results[targetTrackName] = OrderedDict()
                results[targetTrackName][refTrackName] = result

        stat = choices.statistic
        statIndex = STAT_LIST_INDEX[stat]
        title = 'Screening track collections  (' + stat + ')'

        processedResults = []
        headerColumn = []
        for targetTrackName in targetGSuite.allTrackTitles():
            resultRowDict = processRawResults(results[targetTrackName])
            resultColumn = []
            headerColumn = []
            for refTrackName, statList in resultRowDict.iteritems():
                resultColumn.append(statList[statIndex])
                headerColumn.append(refTrackName)
            processedResults.append(resultColumn)

        transposedProcessedResults = [list(x) for x in zip(*processedResults)]

        tableHeader = ['Track names'] + targetGSuite.allTrackTitles()
        htmlCore = HtmlCore()
        htmlCore.begin()
        htmlCore.header(title)
        htmlCore.divBegin('resultsDiv')
        htmlCore.tableHeader(tableHeader, sortable=True, tableId='resultsTable')
        for i, row in enumerate(transposedProcessedResults):
            line = [headerColumn[i]] + [strWithStdFormatting(x) for x in row]
            htmlCore.tableLine(line)
        htmlCore.tableFooter()
        htmlCore.divEnd()

#         #hicharts can't handle strings that contain ' or " as input for series names
        targetTrackNames = [x.replace('\'', '').replace('"','') for x in targetGSuite.allTrackTitles()]
        refTrackNames = [x.replace('\'', '').replace('"','') for x in refGSuite.allTrackTitles()]
# 
#         '''
#         addColumnPlotToHtmlCore(htmlCore, targetTrackNames, refTrackNames,
#                                 stat, title + ' plot',
#                                 processedResults, xAxisRotation = -45, height=800)
#         '''
#         '''
#         addPlotToHtmlCore(htmlCore, targetTrackNames, refTrackNames,
#                                 stat, title + ' plot',
#                                 processedResults, xAxisRotation = -45, height=400)
#         '''
#         
        from quick.webtools.restricted.visualization.visualizationGraphs import visualizationGraphs
        vg = visualizationGraphs()
        result = vg.drawColumnChart(processedResults,
                      height=600,
                      yAxisTitle=stat,
                      categories=refTrackNames,
                      xAxisRotation=90,
                      seriesName=targetTrackNames,
                      shared=False,
                      titleText=title + ' plot',
                      overMouseAxisX=True,
                      overMouseLabelX = ' + this.value.substring(0, 10) +')
        
        htmlCore.line(result)
        #htmlCore.line(vg.visualizeResults(result, htmlCore))
        
        htmlCore.hideToggle(styleClass='debug')
        htmlCore.end()

        print htmlCore
Пример #15
0
    def _generateAnswerText(self, coreCls):
        onlyLocalPvals = self._results.hasOnlyLocalPvals()
        globalPval = self._results.getGlobalResult().get(self._results.getPvalKey()) if not onlyLocalPvals else None

        localPvalsUrl = getRelativeUrlFromWebPath(os.sep.join([self._baseDir, 'table.html'])) #problematic dependency towards fn in tablePresenter..
        #Change to something like this when StaticFile has been used throughout presenters..
        #from quick.util.StaticFile import GalaxyRunSpecificFile
        #GalaxyRunSpecificFile([], '', self._galaxyFn)
        
        core = coreCls()
        core.styleInfoBegin(styleClass="infomessagesmall answerbox question")
        core.header('You asked:')
        core.line(str(coreCls().highlight(self._getHeader())))
        core.styleInfoEnd()
        
        #Simplistic answer
        core.styleInfoBegin(styleClass="infomessagesmall answerbox simplisticanswer")
        core.header(str(coreCls().link('Simplistic answer:', '#', \
                                        args='''onclick="return toggle('simplistic_answer_expl')"''')))
        
        core.styleInfoBegin(styleId="simplistic_answer_expl", styleClass="infomessagesmall explanation")
        if onlyLocalPvals :
            core.line('''
Under "simplistic answer" you will find a simple statement on whether there were any findings for the local analysis. The number of significant bins at 10% false discovery rate (FDR) is provided.<br>
<br>
It is not possible to draw a decisive conclusion based on a p-value, so the statements are only meant as simple indications.<br>
                  ''')
        else:
            core.line('''
Under "simplistic answer" you will find a yes/maybe/no-conclusion answer to the question asked, based on a simple thresholding scheme on the p-value:<br>
"yes" if p-value < 0.01<br>
"maybe" if  0.01 < p-value < 0.1<br>
"no conclusion" if p-value > 0.1<br>
<br>
It is not possible to draw a decisive conclusion based on a p-value, so the statements are only meant as simple indications.<br>                  
                  ''')
            
        core.styleInfoEnd()
        
        if onlyLocalPvals:
            numSign, numTested, numIgnored = self._results.getFdrSignBins()
            if numSign == numTested and numSign != 0:
                simplisticPhrase = 'Yes - the data suggests this for all bins'
            elif numSign>0:
                simplisticPhrase = 'Yes - the data suggests this at least in some bins'
                numSign, numTested, numIgnored = self._results.getFdrSignBins()
                simplisticPhrase += ' (%i significant bins out of %i, at %i%% FDR' % (numSign, numTested, self._results.FDR_THRESHOLD*100)
            else:
                simplisticPhrase = 'No support from data for this conclusion in any bin'
            
                
            core.line(str(coreCls().highlight(simplisticPhrase)))
        else:
            assert globalPval is not None
            
            directionality = ''
            if self._results._analysis.isTwoSidedTest():
                tsValue, expTsValue = self._getTestStatisticAndExpectedValues()
                if tsValue is not None and expTsValue is not None and tsValue!=expTsValue:
                    directionality = '(higher) ' if tsValue > expTsValue else '(lower) '
                    
            if globalPval < 0.01:
                simplisticPhrase = 'Yes %s- the data suggests this' % directionality
            elif globalPval < 0.1:
                simplisticPhrase = 'Maybe %s- weak evidence' % directionality
            else:
                simplisticPhrase = 'No support from data for this conclusion'
                
            core.line(str(coreCls().highlight(simplisticPhrase + ' (p-value: ' + strWithStdFormatting(globalPval) + ')' )))
        core.styleInfoEnd()
        
        #Precise answer
        core.styleInfoBegin(styleClass="infomessagesmall answerbox preciseanswer")
        core.header(str(coreCls().link('Precise answer:', '#', \
                                       args='''onclick="return toggle('precise_answer_expl')"''')))
        
        core.styleInfoBegin(styleId="precise_answer_expl", styleClass="infomessagesmall explanation")
        if onlyLocalPvals :
            core.line('''
Significance testing evaluates a <b>null hypothesis (H0)</b> versus an <b>alternative hypothesis (H1)</b>. Low <b>p-values</b> are evidence against H0. The testing involves comparing the observed value of a  <b>test statistic</b> to the distribution of the test statistic under a <b>null model</b>. The testing was performed in each local bin, with a list of FDR-corrected p-values per bin provided.                  
                  ''')
        else:
            core.line('''
Significance testing evaluates a <b>null hypothesis (H0)</b> versus an <b>alternative hypothesis (H1)</b>. Low <b>p-values</b> are evidence against H0. The testing involves comparing the observed value of a  <b>test statistic</b> to the distribution of the test statistic under a <b>null model</b>. 
                  ''')

        core.styleInfoEnd()
        
        EffectSizeText = 'Please note that both the effect size and the p-value should be considered in order to assess the practical significance of a result.'
        
        FDR_text = '* False Discovery Rate: The expected proportion of false positive results among the significant bins is no more than %i%%.' \
                    % (self._results.FDR_THRESHOLD*100)
        
        if onlyLocalPvals:
            numSign, numTested, numIgnored = self._results.getFdrSignBins()
            
            core.line(str(coreCls().highlight('%i significant bins out of %i, at %i' \
                                              % (numSign, numTested, self._results.FDR_THRESHOLD*100) + '% FDR*')))
            core.line('')
            localPvalsLink = str(coreCls().link('collection of FDR-corrected p-values per bin', localPvalsUrl))
            notComputeLink = str(coreCls().link('Not able to compute', '#', \
                                               args='''onclick="return toggle('no_global_pval_expl')"'''))
            core.line('A ' + localPvalsLink + ' was computed. ' + notComputeLink + ' a global p-value for this analysis.')
            core.styleInfoBegin(styleId="no_global_pval_expl", styleClass="infomessagesmall explanation")
            core.line('(Explanation to appear in box)')
            core.styleInfoEnd()
            
            if numIgnored > 0:
                core.line('')
                core.line('%s bin%s excluded due to lack of data.' % (numIgnored, 's' if numIgnored > 1 else ''))
                
            core.line('')
            core.line(EffectSizeText)
            core.line('')
            core.line(FDR_text)

            h0h1Text = self._getH0andH1Text(coreCls)
            if h0h1Text is not None:
                core.divider(withSpacing=True)
                core.line('In each bin, the test of')
                core.append(h0h1Text)
                core.line('was performed.')
        else:
            h0h1Text = self._getH0andH1Text(coreCls)
            if h0h1Text is not None:
                core.line('The p-value is %s for the test' % strWithStdFormatting(globalPval) )
                core.append(h0h1Text)
            else:
                core.line('The p-value is %s.' % strWithStdFormatting(globalPval) )
                core.line('')
            core.line('Low p-values are evidence against H0.')

            numSign, numTested, numIgnored = self._results.getFdrSignBins()
            if numTested+numIgnored > 1:                
                localPvalsLink = str(coreCls().link('each bin separately', localPvalsUrl))
                excludeText = ' (%i bin%s excluded from FDR-analysis due to lacking p-values).' \
                              % (numIgnored, 's' if numIgnored>1 else '.') if numIgnored>0 else ''
                core.line('')
                core.line('The test was also performed for ' + localPvalsLink + \
                          ', resulting in %i significant bins out of %i, at %i%% FDR*' % (numSign, numTested, self._results.FDR_THRESHOLD*100) +\
                          excludeText)

            core.line('')
            core.line(EffectSizeText)
            core.line('')
            core.line(FDR_text)
        
        nullModel = self._results._analysis.getNullModel()
        if nullModel is not None:
            core.divider(withSpacing=True)
            core.line('P-values were computed under the %s defined by the following preservation and randomization rules:' \
                      % str(coreCls().highlight('null model')))
            core.paragraph(nullModel, indent=True)

        testStatistic = self._results.getTestStatisticText()
        if testStatistic != None:
            #pick out relevant part:
            mo = re.search('^[tT]est.[sS]tatistic ?:? ?',testStatistic)
            if mo!= None:
                testStatistic = testStatistic[mo.end():]            
                #if len(testStatistic)>0 and testStatistic[0]=='(':
                    #testStatistic = testStatistic[1:]
                #if len(testStatistic)>0 and testStatistic[-1]==')':
                    #testStatistic = testStatistic[:-1]
            
            tsValue, expTsValue = self._getTestStatisticAndExpectedValues()
            core.divider(withSpacing=True)
            core.line('The %s used is:' % str(coreCls().highlight('test statistic')))
            core.paragraph(testStatistic, indent=True)
            
            if tsValue is not None:
                if expTsValue is not None:
                    core.line('The value of the test statistic is %s, which is %s the expected value: %s.' \
                                % (strWithStdFormatting(tsValue), \
                                   (str(coreCls().emphasize('higher')) + ' than' if tsValue > expTsValue else \
                                    (str(coreCls().emphasize('lower')) + ' than' if tsValue < expTsValue else \
                                     str(coreCls().emphasize('equal')) + ' to')), \
                                   strWithStdFormatting(expTsValue)))
                else:
                    core.line('The value of the test statistic is %s.' % (strWithStdFormatting(tsValue)))
            
        #temporary solution, as lacking objects needed to construct note-link directly..
        noteText = ''
        if self._results._runDescription is not None:
            #mo = re.search('<note.*note>', self._results._runDescription)
            mo = re.search('<a href[^>]*/notes/[^>]*>[^<]*</a>', self._results._runDescription)
            if mo is not None:
                noteLink = mo.string[mo.start():mo.end()]
                noteText = ' See ' + noteLink + ' for a more complete description of the test.'
        
        if noteText == '':
            logMessage('Note-link not found in runDescription, and thus omitted from results')
            
        core.divider(withSpacing=True)
        
        runDescLink = str(coreCls().link('run description', '#', \
                                         args='''onclick="return toggle('run_description')"'''))
        core.line('The p-values may be subject to further parameter choices, which are listed in the %s.' %\
                  (runDescLink) + noteText)
        core.divider(withSpacing=True)
        resultsLink = str(coreCls().link('See full details', '#', \
                                         args='''onclick="return toggle('results_box')"'''))
        core.line(resultsLink + ' of the results in table form.')
        core.styleInfoEnd()
        
        return str(core)