예제 #1
0
    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.
        '''
        DebugMixin._setDebugModeIfSelected(choices)
        genome = choices.genome
        gSuite = getGSuiteFromGalaxyTN(choices.gsuite)
        #         fullCategory = AnalysisManager.combineMainAndSubCategories(choices.analysisCategory, 'Basic')
        fullCategory = AnalysisManager.combineMainAndSubCategories(
            'Descriptive statistics', 'Basic')
        tracks = list(gSuite.allTracks())
        analysisName = choices.analysis
        # selectedAnalysis = GSuiteSingleValueAnalysisPerTrackTool \
        #     ._resolveAnalysisFromName(gSuite.genome, fullCategory, tracks[0].trackName, analysisName)

        selectedAnalysis = cls.ANALYSIS_PRETTY_NAME_TO_ANALYSIS_SPEC_MAPPING[
            choices.analysis]

        regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices)
        analysisBins = GalaxyInterface._getUserBinSource(regSpec,
                                                         binSpec,
                                                         genome=genome)
        # paramName, paramValues = selectedAnalysis.getFirstOptionKeyAndValues()
        # if paramName and paramValues:
        #     if len(paramValues) == 1:
        #         selectedAnalysis.addParameter(paramName, paramValues[0])
        #     else:
        #         selectedAnalysis.addParameter(paramName, choices.paramOne)

        tableDict = OrderedDict()

        for track in tracks:
            tableDict[track.title] = OrderedDict()
            result = doAnalysis(selectedAnalysis, analysisBins, [track])
            resultDict = result.getGlobalResult()
            if 'Result' in resultDict:
                track.setAttribute(analysisName.lower(),
                                   str(resultDict['Result']))
                tableDict[
                    track.title][analysisName] = strWithNatLangFormatting(
                        resultDict['Result'])
            else:
                for attrName, attrVal in resultDict.iteritems():
                    attrNameExtended = analysisName + ':' + attrName
                    track.setAttribute(attrNameExtended.lower(), str(attrVal))
                    tableDict[track.title][
                        attrNameExtended] = strWithNatLangFormatting(attrVal)
                    # assert isinstance(resultDict['Result'], (int, basestring, float)), type(resultDict['Result'])

        core = HtmlCore()
        core.begin()
        core.header('Results: ' + analysisName)

        def _produceTable(core, tableDict=None, tableId=None):
            return core.tableFromDictOfDicts(tableDict,
                                             firstColName='Track title',
                                             tableId=tableId,
                                             expandable=True,
                                             visibleRows=20,
                                             presorted=0)

        tableId = 'results_table'
        tableFile = GalaxyRunSpecificFile([tableId, 'table.tsv'], galaxyFn)
        tabularHistElementName = 'Raw results: ' + analysisName

        gsuiteFile = GalaxyRunSpecificFile(
            [tableId, 'input_with_results.gsuite'], galaxyFn)
        GSuiteComposer.composeToFile(gSuite, gsuiteFile.getDiskPath())
        gsuiteHistElementName = \
            getGSuiteHistoryOutputName('result', ', ' + analysisName, choices.gsuite)

        core.tableWithImportButtons(
            tabularFile=True,
            tabularFn=tableFile.getDiskPath(),
            tabularHistElementName=tabularHistElementName,
            gsuiteFile=True,
            gsuiteFn=gsuiteFile.getDiskPath(),
            gsuiteHistElementName=gsuiteHistElementName,
            produceTableCallbackFunc=_produceTable,
            tableDict=tableDict,
            tableId=tableId)
        core.end()
        print core
예제 #2
0
    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.
        '''
        import numpy
        numpy.seterr(all='raise')
        cls._setDebugModeIfSelected(choices)
        # DebugUtil.insertBreakPoint(username=username, currentUser='******')
        genome = choices.genome
        analysisQuestion = choices.analysisName
        similaryStatClassName = choices.similarityFunc if choices.similarityFunc else GSuiteStatUtils.T5_RATIO_OF_OBSERVED_TO_EXPECTED_OVERLAP
        summaryFunc = choices.summaryFunc if choices.summaryFunc else 'average'
        reverse = 'Yes' if choices.reversed else 'No'

        gsuite = getGSuiteFromGalaxyTN(choices.gsuite)
        regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices)
        analysisBins = GalaxyInterface._getUserBinSource(regSpec,
                                                         binSpec,
                                                         genome=genome)
        tracks = [
            Track(x.trackName, trackTitle=x.title) for x in gsuite.allTracks()
        ]
        trackTitles = CommonConstants.TRACK_TITLES_SEPARATOR.join(
            [quote(x.title, safe='') for x in gsuite.allTracks()])

        additionalResultsDict = OrderedDict()
        additionalAttributesDict = OrderedDict()
        if analysisQuestion in [cls.Q1, cls.Q2, cls.Q3]:
            additionalAttributesDict = cls.getSelectedAttributesForEachTrackDict(
                choices.additionalAttributes, gsuite)
            #additional analysis
            stats = [CountStat, CountElementStat]
            additionalResultsDict = runMultipleSingleValStatsOnTracks(
                gsuite, stats, analysisBins, queryTrack=None)

        if analysisQuestion == cls.Q1:
            analysisSpec = AnalysisSpec(
                GSuiteRepresentativenessOfTracksRankingsWrapperStat)
            analysisSpec.addParameter(
                'pairwiseStatistic', GSuiteStatUtils.
                PAIRWISE_STAT_LABEL_TO_CLASS_MAPPING[similaryStatClassName])
            analysisSpec.addParameter(
                'summaryFunc',
                GSuiteStatUtils.SUMMARY_FUNCTIONS_MAPPER[summaryFunc])
            analysisSpec.addParameter('reverse', reverse)
            analysisSpec.addParameter('ascending', 'No')
            analysisSpec.addParameter('trackTitles', trackTitles)
            results = doAnalysis(analysisSpec, analysisBins,
                                 tracks).getGlobalResult()

            gsPerTrackResultsModel = GSuitePerTrackResultModel(
                results,
                ['Similarity to rest of tracks in suite (%s)' % summaryFunc],
                additionalResultsDict=additionalResultsDict,
                additionalAttributesDict=additionalAttributesDict)
            if choices.leadAttribute and choices.leadAttribute != GSuiteConstants.TITLE_COL:
                columnTitles, decoratedResultsDict = \
                    gsPerTrackResultsModel.generateColumnTitlesAndResultsDict(choices.leadAttribute)
            else:
                columnTitles, decoratedResultsDict = \
                    gsPerTrackResultsModel.generateColumnTitlesAndResultsDict()

            core = HtmlCore()
            core.begin()
            core.divBegin(divId='results-page')
            core.divBegin(divClass='results-section')
            core.header(analysisQuestion)
            topTrackTitle = results.keys()[0]
            core.paragraph('''
                The track "%s" is the most representative track of the GSuite with %s %s similarity to the rest of the tracks
                as measured by "%s" track similarity measure.
            ''' % (topTrackTitle, results[topTrackTitle], summaryFunc,
                   similaryStatClassName))

            addTableWithTabularAndGsuiteImportButtons(
                core,
                choices,
                galaxyFn,
                cls.Q1_SHORT,
                decoratedResultsDict,
                columnTitles,
                gsuite=gsuite,
                results=results,
                gsuiteAppendAttrs=['similarity_score'],
                sortable=True)

            # plot
            columnInd = 0
            if choices.leadAttribute and choices.leadAttribute != GSuiteConstants.TITLE_COL:
                columnInd = 1
            res = GSuiteTracksCoincidingWithQueryTrackTool.drawPlot(
                results,
                additionalResultsDict,
                'Similarity to rest of tracks in suite (%s)' % summaryFunc,
                columnInd=columnInd)
            core.line(res)
            core.divEnd()
            core.divEnd()
            core.end()

        # elif analysisQuestion == cls.Q2:
        #     analysisSpec = AnalysisSpec(GSuiteRepresentativenessOfTracksRankingsWrapperStat)
        #     analysisSpec.addParameter('pairwiseStatistic', GSuiteStatUtils.PAIRWISE_STAT_LABEL_TO_CLASS_MAPPING[similaryStatClassName])
        #     analysisSpec.addParameter('summaryFunc', GSuiteStatUtils.SUMMARY_FUNCTIONS_MAPPER[summaryFunc])
        #     analysisSpec.addParameter('reverse', reverse)
        #     analysisSpec.addParameter('ascending', 'Yes')
        #     analysisSpec.addParameter('trackTitles', trackTitles)
        #     results = doAnalysis(analysisSpec, analysisBins, tracks).getGlobalResult()
        #
        #     gsPerTrackResultsModel = GSuitePerTrackResultModel(
        #         results, ['Similarity to rest of tracks in suite (%s)' % summaryFunc],
        #         additionalResultsDict=additionalResultsDict,
        #         additionalAttributesDict=additionalAttributesDict)
        #     if choices.leadAttribute and choices.leadAttribute != GSuiteConstants.TITLE_COL:
        #         columnTitles, decoratedResultsDict = \
        #             gsPerTrackResultsModel.generateColumnTitlesAndResultsDict(choices.leadAttribute)
        #     else:
        #         columnTitles, decoratedResultsDict = \
        #             gsPerTrackResultsModel.generateColumnTitlesAndResultsDict()
        #
        #     core = HtmlCore()
        #     core.begin()
        #     core.divBegin(divId='results-page')
        #     core.divBegin(divClass='results-section')
        #     core.header(analysisQuestion)
        #     topTrackTitle = results.keys()[0]
        #     core.paragraph('''
        #         The track "%s" is the most atypical track of the GSuite with %s %s similarity to the rest of the tracks
        #         as measured by the "%s" track similarity measure.
        #     ''' % (topTrackTitle, strWithNatLangFormatting(results[topTrackTitle]), summaryFunc, similaryStatClassName))
        #     # core.tableFromDictionary(results, columnNames=['Track title', 'Similarity to rest of tracks in suite (' + summaryFunc+')'], sortable=False)
        #
        #     from quick.util import CommonFunctions
        #     rawDataURIList = CommonFunctions.getHyperlinksForRawTableData(
        #         dataDict=decoratedResultsDict, colNames=columnTitles,
        #         tableId="resultsTable", galaxyFn=galaxyFn)
        #     core.tableFromDictionary(decoratedResultsDict, columnNames=columnTitles, sortable=True,
        #                              tableId='resultsTable', addInstruction=True,
        #                              addRawDataSelectBox=True, rawDataURIList=rawDataURIList)
        #     # core.tableFromDictionary(decoratedResultsDict, columnNames=columnTitles, sortable=True, tableId='resultsTable')
        #
        #     columnInd = 0
        #     if choices.leadAttribute and choices.leadAttribute != GSuiteConstants.TITLE_COL:
        #         columnInd = 1
        #     res = GSuiteTracksCoincidingWithQueryTrackTool.drawPlot(
        #         results, additionalResultsDict,
        #         'Similarity to rest of tracks in suite (%s)' % summaryFunc,
        #         columnInd=columnInd)
        #     core.line(res)
        #     core.divEnd()
        #     core.divEnd()
        #     core.end()
        #
        #     if choices.addResults == 'Yes':
        #         GSuiteStatUtils.addResultsToInputGSuite(
        #             gsuite, results, ['Similarity_score'],
        #             cls.extraGalaxyFn[GSUITE_EXPANDED_WITH_RESULT_COLUMNS_FILENAME])
        elif analysisQuestion == cls.Q3:

            mcfdrDepth = choices.mcfdrDepth if choices.mcfdrDepth else \
            AnalysisDefHandler(REPLACE_TEMPLATES['$MCFDR$']).getOptionsAsText().values()[0][0]

            analysisDefString = REPLACE_TEMPLATES[
                '$MCFDRv3$'] + ' -> GSuiteRepresentativenessOfTracksRankingsAndPValuesWrapperStat'
            analysisSpec = AnalysisDefHandler(analysisDefString)
            analysisSpec.setChoice('MCFDR sampling depth', mcfdrDepth)
            analysisSpec.addParameter('assumptions',
                                      'PermutedSegsAndIntersegsTrack')
            analysisSpec.addParameter(
                'rawStatistic',
                SummarizedInteractionWithOtherTracksV2Stat.__name__)
            analysisSpec.addParameter(
                'pairwiseStatistic', GSuiteStatUtils.
                PAIRWISE_STAT_LABEL_TO_CLASS_MAPPING[similaryStatClassName])
            analysisSpec.addParameter(
                'summaryFunc',
                GSuiteStatUtils.SUMMARY_FUNCTIONS_MAPPER[summaryFunc])
            analysisSpec.addParameter('tail', 'right-tail')
            analysisSpec.addParameter('trackTitles', trackTitles)
            results = doAnalysis(analysisSpec, analysisBins,
                                 tracks).getGlobalResult()
            core = HtmlCore()

            gsPerTrackResultsModel = GSuitePerTrackResultModel(
                results, [
                    'Similarity to rest of tracks in suite (%s)' % summaryFunc,
                    'P-value'
                ],
                additionalResultsDict=additionalResultsDict,
                additionalAttributesDict=additionalAttributesDict)
            if choices.leadAttribute and choices.leadAttribute != GSuiteConstants.TITLE_COL:
                columnTitles, decoratedResultsDict = \
                    gsPerTrackResultsModel.generateColumnTitlesAndResultsDict(choices.leadAttribute)
            else:
                columnTitles, decoratedResultsDict = \
                    gsPerTrackResultsModel.generateColumnTitlesAndResultsDict()

            core.begin()
            core.divBegin(divId='results-page')
            core.divBegin(divClass='results-section')
            core.header(analysisQuestion)
            topTrackTitle = results.keys()[0]
            core.paragraph('''
                The track "%s" has the lowest P-value of %s corresponding to %s %s similarity to the rest of the tracks
                as measured by "%s" track similarity measure.
            ''' % (topTrackTitle,
                   strWithNatLangFormatting(results[topTrackTitle][1]),
                   strWithNatLangFormatting(results[topTrackTitle][0]),
                   summaryFunc, similaryStatClassName))
            # core.tableFromDictionary(results, columnNames=['Track title', 'Similarity to rest of tracks in suite (' + summaryFunc+')', 'P-value'], sortable=False)

            addTableWithTabularAndGsuiteImportButtons(
                core,
                choices,
                galaxyFn,
                cls.Q3_SHORT,
                decoratedResultsDict,
                columnTitles,
                gsuite=gsuite,
                results=results,
                gsuiteAppendAttrs=['similarity_score', 'p_value'],
                sortable=True)

            core.divEnd()
            core.divEnd()
            core.end()
        else:  # Q4
            mcfdrDepth = choices.mcfdrDepth if choices.mcfdrDepth else \
                AnalysisDefHandler(REPLACE_TEMPLATES['$MCFDR$']).getOptionsAsText().values()[0][0]
            analysisDefString = REPLACE_TEMPLATES[
                '$MCFDRv3$'] + ' -> CollectionSimilarityHypothesisWrapperStat'
            analysisSpec = AnalysisDefHandler(analysisDefString)
            analysisSpec.setChoice('MCFDR sampling depth', mcfdrDepth)
            analysisSpec.addParameter('assumptions',
                                      'PermutedSegsAndIntersegsTrack')
            analysisSpec.addParameter('rawStatistic',
                                      'MultitrackSummarizedInteractionV2Stat')
            analysisSpec.addParameter(
                'pairwiseStatistic', GSuiteStatUtils.
                PAIRWISE_STAT_LABEL_TO_CLASS_MAPPING[similaryStatClassName])
            analysisSpec.addParameter(
                'summaryFunc',
                GSuiteStatUtils.SUMMARY_FUNCTIONS_MAPPER[summaryFunc])
            analysisSpec.addParameter('multitrackSummaryFunc',
                                      'avg')  # should it be a choice?
            analysisSpec.addParameter('tail', 'right-tail')
            results = doAnalysis(analysisSpec, analysisBins,
                                 tracks).getGlobalResult()
            pval = results['P-value']
            observed = results['TSMC_MultitrackSummarizedInteractionV2Stat']
            significanceLevel = 'strong' if pval < 0.01 else (
                'weak' if pval < 0.05 else 'no')
            core = HtmlCore()
            core.begin()
            core.divBegin(divId='results-page')
            core.divBegin(divClass='results-section')
            core.header(analysisQuestion)
            core.paragraph('''
                The tracks in the suite show %s significance in their collective similarity
                (average similarity of a track to the rest) of %s
                and corresponding p-value of %s,
                as measured by "%s" track similarity measure.
            ''' % (significanceLevel, strWithNatLangFormatting(observed),
                   strWithNatLangFormatting(pval), similaryStatClassName))
            core.divEnd()
            core.divEnd()
            core.end()

        print 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.
        '''
        genome = choices.genome
        targetTrack = ExternalTrackManager.getPreProcessedTrackFromGalaxyTN(
            genome,
            choices.targetTrack,
            printErrors=False,
            printProgress=False)

        refGSuite = getGSuiteFromGalaxyTN(choices.refTrackCollection)

        regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices)

        analysisBins = GalaxyInterface._getUserBinSource(regSpec,
                                                         binSpec,
                                                         genome=genome)

        results = TrackReportCommon.getOverlapResultsForTrackVsCollection(
            genome, targetTrack, refGSuite, analysisBins=analysisBins)
        processedResults = TrackReportCommon.processRawResults(results)

        targetTrackTitle = prettyPrintTrackName(targetTrack)
        title = 'Screening of track ' + targetTrackTitle
        sortedProcessedResultsTupleList = sorted(
            processedResults.iteritems(),
            key=lambda x: x[1][STAT_LIST_INDEX[STAT_FACTOR_OBSERVED_VS_EXPECTED
                                               ]],
            reverse=True)
        refTrackNames = [x[0] for x in sortedProcessedResultsTupleList]
        refTrackNames = [
            x.replace('\'', '').replace('"', '') for x in refTrackNames
        ]
        plotData = [x[1] for x in sortedProcessedResultsTupleList]
        #         plotData = zip(*plotData) #invert
        plotData = normalizeMatrixData(plotData)

        printVals = tuple([str(targetTrackTitle)]) + tuple(
            [str(x[0]) for x in sortedProcessedResultsTupleList[0:3]])

        htmlCore = HtmlCore()
        htmlCore.begin()
        htmlCore.header(title)

        if choices.bmQid and choices.bmQid not in ['None']:
            htmlCore.append(
                str(
                    quick.gsuite.GSuiteHbIntegration.
                    getAnalysisQuestionInfoHtml(choices.bmQid)))

        htmlCore.divBegin('resultsDiv')
        htmlCore.paragraph('''
            The query track <b>%s</b> overlaps most strongly (is most highly enriched) with the tracks <b>%s</b>, <b>%s</b> and <b>%s</b> 
            from the selected collection. See below for a full (ranked) table of overlap and enrichment.
        ''' % printVals)

        htmlCore.paragraph('''
        The coverage of the query track is %s bps.
        ''' % strWithNatLangFormatting(
            TrackReportCommon.getQueryTrackCoverageFromRawOverlapResults(
                results)))

        htmlCore.tableHeader(TrackReportCommon.HEADER_ROW,
                             sortable=True,
                             tableId='resultsTable')
        for refTrackName, refTrackResults in sortedProcessedResultsTupleList:
            line = [refTrackName
                    ] + [strWithNatLangFormatting(x) for x in refTrackResults]
            htmlCore.tableLine(line)
        htmlCore.tableFooter()
        htmlCore.divEnd()
        '''

        addColumnPlotToHtmlCore(htmlCore, 
                                refTrackNames,  
                                TrackReportCommon.HEADER_ROW[1:], 
                                'stat', 'Results plot (data is normalized for better visual comparison) ', 
                                plotData, xAxisRotation = 315)
        '''
        addPlotToHtmlCore(
            htmlCore,
            refTrackNames,
            TrackReportCommon.HEADER_ROW[1:],
            'stat',
            'Results plot (data is normalized for better visual comparison) ',
            plotData,
            xAxisRotation=315)

        htmlCore.hideToggle(styleClass='debug')
        htmlCore.end()

        print htmlCore
    def execute(cls, choices, galaxyFn=None, username=''):
        cls._setDebugModeIfSelected(choices)

        genome = choices.genome
        genomicRegionsSource = choices.genomicRegionsSource
        genomicRegions = choices.genomicRegions
        #upFlankSize = int(choices.upFlankSize)
        #downFlankSize = int(choices.downFlankSize)
        sourceTfs = choices.sourceTfs
        tfTracks = choices.tfTracks

        # Get TF track name:
        if sourceTfs == cls.REGIONS_FROM_HISTORY:
            galaxyTN = tfTracks.split(':')
            tfTrackName = ExternalTrackManager.getPreProcessedTrackFromGalaxyTN(
                genome, galaxyTN)
        else:
            tfTrackName = TfTrackNameMappings.getTfTrackNameMappings(
                genome)[sourceTfs] + [tfTracks]

        # Get Genomic Regions track names:
        selectedTrackNames = []

        if isinstance(genomicRegions, dict):
            selectedGenRegions = [
                key for key, val in genomicRegions.iteritems() if val == 'True'
            ]
        else:
            selectedGenRegions = genomicRegions

        if genomicRegionsSource == 'Hyperbrowser repository (single tracks)':
            for i in selectedGenRegions:
                selectedTrackNames.append(
                    TfbsTrackNameMappings.getTfbsTrackNameMappings(genome)[i])
        elif genomicRegionsSource == 'Hyperbrowser repository (cell-specific multi-tracks)':
            for i in selectedGenRegions:
                genElementGSuiteName = TfbsGSuiteNameMappings.getTfbsGSuiteNameMappings(
                    genome)[i]
                gSuite = getGSuiteFromGSuiteFile(genElementGSuiteName)
                for track in gSuite.allTracks():
                    selectedTrackNames.append(track.trackName)
        elif genomicRegionsSource == 'History (user-defined)':
            if genomicRegions.split(":")[1] == "gsuite":
                gSuite = getGSuiteFromGalaxyTN(selectedGenRegions)
                for track in gSuite.allTracks():
                    selectedTrackNames.append(track.trackName)
            else:
                galaxyTN = selectedGenRegions.split(':')
                gRegTrackName = ExternalTrackManager.getPreProcessedTrackFromGalaxyTN(
                    genome, galaxyTN)
                selectedTrackNames.append(gRegTrackName)
        else:
            return

        #Intersection:
        title = 'Targets of ' + tfTrackName[-1] + ' TF track'
        htmlCore = HtmlCore()
        htmlCore.begin()
        htmlCore.header(title)
        htmlCore.divBegin('resultsDiv')
        htmlCore.tableHeader([
            'Genomic Region', 'Number of Target Regions',
            'Download bed file of Target Regions', 'Send bed file to history'
        ],
                             sortable=True,
                             tableId='resultsTable')

        n = 0
        allTargetBins = []
        dataY = []
        allRefSetNames = []
        #print 'all:', selectedTrackNames, '<p>'
        #print 'tf:', tfTrackName, '<p>'
        for i in selectedTrackNames:
            n = n + 1
            #newGalaxyFn = galaxyFn.split(".")[0] + str(n) + "." + "dat"

            tfIntersection = TrackIntersection(genome, i, tfTrackName,
                                               galaxyFn, str(n))
            #tfIntersection.expandReferenceTrack(upFlankSize, downFlankSize)
            regFileNamer = tfIntersection.getIntersectedRegionsStaticFileWithContent(
            )
            targetBins = tfIntersection.getIntersectedReferenceBins()
            '''print 'Target Bins = ', targetBins, '<p>'
            if genomicRegionsSource=='Hyperbrowser repository (single tracks)':
                print '\"', tfTracks, '\" in \"', ":".join((i[len(i)-2],i[len(i)-1])), '":<p>'
            elif genomicRegionsSource=='History (user-defined)':
                print '\"', tfTracks, '\" in \"', i[len(i)-1], '":<p>'
            else:
                listGenRegion = i[0].split(":")
                maxIndex = len(listGenRegion)-1
                print '\"', tfTracks, '\" in \"', ":".join((listGenRegion[maxIndex-1],listGenRegion[maxIndex])), '":<p>'
            print '<p>Number of Targets = ', len(targetBins), 'regions.</p>'
            print '<p>', regFileNamer.getLink('Download bed-file'), ' of all regions with 1 or more hits.</p>'
            print '<p>', regFileNamer.getLoadToHistoryLink('Download bed-file to History'), ' of all regions with 1 or more hits.</p>'
            print '<p>==============================================</p>'
            #with open(galaxyFn, 'w') as outFile:
                #print>>outFile, 'TargetBins=', targetBins, '<p>'
                #print >>outFile, selectedGenRegions, '<p>' '''
            # Collect all target bins and data to plot:
            allTargetBins = allTargetBins + targetBins
            dataY = dataY + [
                TrackIntersection.prepareDataForPlot(genome, targetBins)
            ]
            refSetName = i[len(i) - 1]
            allRefSetNames = allRefSetNames + [refSetName]

            # Print output to table:
            line = [refSetName] + [len(targetBins)] + [
                regFileNamer.getLink('Download bed-file')
            ] + [
                regFileNamer.getLoadToHistoryLink(
                    'Download bed-file to History')
            ]
            #print line, '<p>'
            htmlCore.tableLine(line)

        line = ['Total'] + [len(allTargetBins)] + [''] + ['']
        dataY = dataY + [
            TrackIntersection.prepareDataForPlot(genome, allTargetBins)
        ]
        allRefSetNames = allRefSetNames + ['Total']

        htmlCore.tableLine(line)
        htmlCore.tableFooter()
        htmlCore.divEnd()
        htmlCore.hideToggle(styleClass='debug')
        htmlCore.end()
        print htmlCore
        #print 'ALL Target Bins = ', allTargetBins, '<p>'
        #print 'dataY = ', dataY, '<p>'

        # Plot:
        if genome == 'hg19':
            chrNames = [
                'chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8',
                'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15',
                'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22',
                'chrX', 'chrY'
            ]
        if genome == 'mm9':
            chrNames = [
                'chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8',
                'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15',
                'chr16', 'chr17', 'chr18', 'chr19', 'chrX', 'chrY'
            ]

        titleText = 'Targets per Chromosome'
        dataX = [[dataY[i][j] for i in range(len(dataY))]
                 for j in range(len(dataY[0]))]
        seriesType = ['column'] * len(dataX)
        categories = allRefSetNames
        yAxisTitle = 'Number of Targets'
        seriesName = chrNames
        shared = False
        legend = True
        xAxisRotation = 0
        #print 'dataX = ', dataX, '<p>'

        htmlCore = HtmlCore()
        htmlCore.begin()
        title = 'Targets of ' + tfTrackName[-1] + ' TF track per chromosome'
        htmlCore.header(title)
        htmlCore.line('<a href="#" id="linkContainer1">Click to see plot</a>')
        htmlCore.divBegin(divId='plotDiv', style=' margin: 0 auto')
        htmlCore.line(vp.addJSlibs())
        htmlCore.line(vp.useThemePlot())
        htmlCore.line(vp.addJSlibsExport())
        plot = vp.drawChart(dataX,
                            type='column',
                            legend=legend,
                            height=600,
                            xAxisRotation=xAxisRotation,
                            seriesType=seriesType,
                            seriesName=seriesName,
                            shared=shared,
                            titleText=titleText,
                            overMouseAxisX=True,
                            categories=categories,
                            showChartClickOnLink=True)
        htmlCore.line(plot)
        htmlCore.divEnd()
        htmlCore.end()
        print htmlCore
    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.
        '''

        cls._setDebugModeIfSelected(choices)
        genome = choices.genome
        queryGSuite = getGSuiteFromGalaxyTN(choices.queryGSuite)
        refGSuite = getGSuiteFromGalaxyTN(choices.refGSuite)
        if choices.similarityFunc:
            similarityStatClassNameKey = choices.similarityFunc
        else:
            similarityStatClassNameKey = GSuiteStatUtils.T5_RATIO_OF_OBSERVED_TO_EXPECTED_OVERLAP

        isPointsVsSegments, pointsGSuite, segGSuite = cls.isPointsVsSegmentsAnalysis(
            queryGSuite, refGSuite)

        regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices)
        analysisBins = GalaxyInterface._getUserBinSource(regSpec,
                                                         binSpec,
                                                         genome=genome)

        queryTrackList = [
            Track(x.trackName, x.title) for x in queryGSuite.allTracks()
        ]
        refTrackList = [
            Track(x.trackName, x.title) for x in refGSuite.allTracks()
        ]

        queryTrackTitles = CommonConstants.TRACK_TITLES_SEPARATOR.join(
            [quote(x.title, safe='') for x in queryGSuite.allTracks()])
        refTrackTitles = CommonConstants.TRACK_TITLES_SEPARATOR.join(
            [quote(x.title, safe='') for x in refGSuite.allTracks()])

        analysisSpec = AnalysisSpec(GSuiteVsGSuiteWrapperStat)
        analysisSpec.addParameter('queryTracksNum', str(len(queryTrackList)))
        analysisSpec.addParameter('refTracksNum', str(len(refTrackList)))
        analysisSpec.addParameter('queryTrackTitleList', queryTrackTitles)
        analysisSpec.addParameter('refTrackTitleList', refTrackTitles)
        analysisSpec.addParameter(
            'similarityStatClassName', GSuiteStatUtils.
            PAIRWISE_STAT_LABEL_TO_CLASS_MAPPING[similarityStatClassNameKey])
        if choices.removeZeroRow:
            analysisSpec.addParameter('removeZeroRow', choices.removeZeroRow)
        if choices.removeZeroCol:
            analysisSpec.addParameter('removeZeroColumn',
                                      choices.removeZeroCol)
        resultsObj = doAnalysis(analysisSpec, analysisBins,
                                queryTrackList + refTrackList)
        results = resultsObj.getGlobalResult()

        # baseDir = GalaxyRunSpecificFile([RAW_OVERLAP_TABLE_RESULT_KEY], galaxyFn).getDiskPath()
        # rawOverlapHeatmapPresenter = HeatmapFromDictOfDictsPresenter(resultsObj, baseDir,
        #                                                              'Overlapping base-pair of tracks from the two suites',
        #                                                              printDimensions=False)

        rawOverlapTableData = results[RAW_OVERLAP_TABLE_RESULT_KEY]
        maxRawOverlap, maxROt1, maxROt2 = rawOverlapTableData.getMaxElement()
        similarityScoreTableData = results[SIMILARITY_SCORE_TABLE_RESULT_KEY]
        maxSimScore, maxSSt1, maxSSt2 = similarityScoreTableData.getMaxElement(
        )

        baseDir = GalaxyRunSpecificFile([], galaxyFn=galaxyFn).getDiskPath()
        overlapHeatmapPresenter = HeatmapFromTableDataPresenter(
            resultsObj,
            baseDir=baseDir,
            header=
            'Overlapping base-pairs between the tracks of the two suites',
            printDimensions=False)
        similarityHeatmapPresenter = HeatmapFromTableDataPresenter(
            resultsObj,
            baseDir=baseDir,
            header='Similarity score between the tracks of the two suites',
            printDimensions=False)
        overlapTablePresenter = MatrixGlobalValueFromTableDataPresenter(
            resultsObj,
            baseDir=baseDir,
            header=
            'Table of overlapping base-pairs between the tracks of the two suites'
        )
        similarityTablePresenter = MatrixGlobalValueFromTableDataPresenter(
            resultsObj,
            baseDir=baseDir,
            header=
            'Table of similarity scores between the tracks of the two suites')

        core = HtmlCore()
        core.begin()
        core.divBegin(divId='results-page')
        core.divBegin(divId='svs-res-main-div', divClass='svs-res-main')
        core.divBegin(divId='raw-overlap-div', divClass='results-section')
        core.divBegin(divId='raw-overlap-table', divClass='svs-table-div')
        core.header('Base-pair overlaps between the tracks of the two GSuites')
        core.paragraph(
            """From the tracks in the two GSuites the highest base-pair overlap <b>(%s bps)</b>
        is observed for the pair of <b>'%s'</b> and <b>'%s'</b>.""" %
            (maxRawOverlap, maxROt1, maxROt2))

        core.divBegin(divId='raw-table-result', divClass='result-div')
        core.divBegin(divId='raw-table-result', divClass='result-div-left')
        core.line('''Follow the links to view the results in an HTML table
        or raw tabular form:''')
        core.divEnd()
        core.divBegin(divId='raw-table-result', divClass='result-div-right')
        core.line(
            overlapTablePresenter.getReference(RAW_OVERLAP_TABLE_RESULT_KEY))
        core.divEnd()  #rawoverlap table
        core.divEnd()
        core.divEnd()
        core.divBegin(divId='raw-overlap-heatmap', divClass='svs-heatmap-div')
        try:
            core.header('Heatmap of base-pair overlaps')
            core.divBegin(divId='raw-table-result',
                          divClass='result-div-heatmap')
            core.divBegin(divId='raw-table-result', divClass='result-div-left')
            core.line(
                '''Follow the links to view the heatmap in the desired format:'''
            )
            core.divEnd()
            core.divBegin(divId='raw-table-result',
                          divClass='result-div-right')
            core.line(
                overlapHeatmapPresenter.getReference(
                    RAW_OVERLAP_TABLE_RESULT_KEY))
            core.divEnd()
            core.divEnd()
        except:
            core.line(
                'Heatmap for the base-pair overlaps could not be created.')
            core.divEnd()
            core.divEnd()
        core.divEnd()  #rawoverlap heatmap
        core.divEnd()  #rawoverlap

        core.divBegin(divId='sim-score-div', divClass='results-section')
        core.divBegin(divId='sim-score-table', divClass='svs-table-div')
        core.header(
            'Similarity score between the tracks of the two GSuites measured by %s'
            % choices.similarityFunc)
        core.paragraph(
            """From the tracks in the two GSuites the highest similarity score <b>(%s)</b>
        is observed for the pair of <b>'%s'</b> and <b>'%s'</b>.""" %
            (maxSimScore, maxSSt1, maxSSt2))
        core.divBegin(divId='raw-table-result', divClass='result-div')
        core.divBegin(divId='raw-table-result', divClass='result-div-left')
        core.line(
            """Follow the links to view the results in an HTML table or raw tabular form:"""
        )
        core.divEnd()
        core.divBegin(divId='raw-table-result', divClass='result-div-right')
        core.line(
            similarityTablePresenter.getReference(
                SIMILARITY_SCORE_TABLE_RESULT_KEY))
        core.divEnd()
        core.divEnd()
        core.divEnd()  #simscore table
        core.divBegin(divId='sim-score-heatmap', divClass='svs-heatmap-div')
        try:
            core.header('Heatmap of similarity scores')
            core.divBegin(divId='raw-table-result',
                          divClass='result-div-heatmap')
            core.divBegin(divId='raw-table-result', divClass='result-div-left')
            core.line(
                '''Follow the links to view the heatmap in the desired format:'''
            )
            core.divEnd()
            core.divBegin(divId='raw-table-result',
                          divClass='result-div-right')
            core.line(
                similarityHeatmapPresenter.getReference(
                    SIMILARITY_SCORE_TABLE_RESULT_KEY))
            core.divEnd()
            core.divEnd()
        except:
            core.line('Heatmap for the similarity score could not be created.')
            core.divEnd()
            core.divEnd()
        core.divEnd()  #simscore heatmap
        core.divEnd()  #simscore
        core.divEnd()  #results
        # core.paragraph(
        #     '''Table displaying the number of base-pairs overlapping between the tracks in the two suites:''')
        # core.tableFromDictOfDicts(rawOverlapTableData, firstColName='Track title')
        # # core.paragraph(rawOverlapHeatmapPresenter.getReference(resDictKey=RAW_OVERLAP_TABLE_RESULT_KEY))
        # core.paragraph(
        #     '''Table displaying the similarity score for the tracks in the two suites as measured by %s:''' % similarityStatClassNameKey)
        # core.tableFromDictOfDicts(similarityScoreTableData, firstColName='Track title')
        #
        core.divEnd()
        core.end()

        print str(core)