def _getTrackData(choices):
        trackTitles1, trackNames1, genome = getGSuiteDataFromGalaxyTN(
            choices.histElement1)
        trackTitles2, trackNames2 = getGSuiteDataFromGalaxyTN(
            choices.histElement2)[:2]
        trackTitles = trackTitles1 + trackTitles2
        trackNames = trackNames1 + trackNames2

        return trackTitles, trackNames, genome, len(trackNames1)
    def execute(choices, galaxyFn=None, username=''):

        genome = choices.targetTrackGenome
        queryTrackName = choices.targetTrack.split(':')

        from quick.multitrack.MultiTrackCommon import getGSuiteDataFromGalaxyTN
        trackTitles, refTrackNameList, genome = getGSuiteDataFromGalaxyTN(choices.refTrackCollection)

        regSpec = 'track'
        binSpec = choices.targetTrack

        #future iter1
        #regSpec, binSpec = UserBinSelector.getRegsAndBinsSpec(choices)

        results = []
        for refTrack in refTrackNameList:
            analysisDef = '-> ProportionCountStat'
            res = GalaxyInterface.runManual([refTrack], analysisDef, regSpec, binSpec, genome, username=username, galaxyFn=galaxyFn) # res is of class Results
            segCoverageProp = [res[seg]['Result'] for seg in res.getAllRegionKeys()]#to heatmap
            results.append(segCoverageProp)


        geSource = FullTrackGenomeElementSource(genome,  queryTrackName)
        modGeSource = MyElementModifier(geSource, results, genome)
        composer = BedComposer(modGeSource, extraTrackLineAttributes={'itemRgb': '"On"'})
        composer.composeToFile(galaxyFn)
Exemplo n.º 3
0
    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)
        assert targetTrackGenome == refTrackCollectionGenome, 'Reference genome must be the same one in both GSuite files.'
        refTracksDict = OrderedDict(zip(refTrackNames, refTrackCollection))

        regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices)

        analysisDef = 'dummy -> RawOverlapStat'
        results = OrderedDict()
        for targetTrackName, targetTrack in targetTracksDict.iteritems():
            for refTrackName, refTrack in refTracksDict.iteritems():
                result = GalaxyInterface.runManual([targetTrack, refTrack],
                                                   analysisDef,
                                                   regSpec,
                                                   binSpec,
                                                   targetTrackGenome,
                                                   galaxyFn,
                                                   printRunDescription=False,
                                                   printResults=False)
                if targetTrackName not in results:
                    results[targetTrackName] = OrderedDict()
                results[targetTrackName][
                    refTrackName] = result.getGlobalResult()

        targetTrackTitles = results.keys()

        stat = choices.statistic
        statIndex = STAT_LIST_INDEX[stat]
        title = stat + ' analysis of track collections'

        processedResults = []
        headerColumn = []
        for targetTrackName in targetTrackTitles:
            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'] + targetTrackTitles
        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]] + row
            htmlCore.tableLine(line)
        htmlCore.tableFooter()
        htmlCore.divEnd()

        addColumnPlotToHtmlCore(htmlCore,
                                targetTrackNames,
                                refTrackNames,
                                stat,
                                title + ' plot',
                                processedResults,
                                xAxisRotation=315)

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

        print htmlCore
Exemplo n.º 4
0
    def execute(cls, choices, galaxyFn=None, username=''):
        genome = choices.genome
         

        from quick.multitrack.MultiTrackCommon import getGSuiteDataFromGalaxyTN
        trackTitles, refTrackNameList, genome = getGSuiteDataFromGalaxyTN(choices.gsuite)
        
        queryTrackName = ExternalTrackManager.extractFnFromGalaxyTN(choices.targetTrack)
        if choices.isBasic:
            suffix = ExternalTrackManager.extractFileSuffixFromGalaxyTN(choices.targetTrack, False)
            regSpec = suffix
            binSpec = queryTrackName
        else:
            regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices)
        
        #targetTrack = choices.targetTrack.split(':')
        #targetTrackTitle = targetTrack[-1]
        #print targetTrackTitle
        #
        #binSpec = targetTrackTitle
        #Phenotype and disease associations:Assorted experiments:Virus integration, HPV specific, Kraus and Schmitz, including 50kb flanks

        from gold.gsuite.GSuiteConstants import TITLE_COL
        from gold.gsuite.GSuite import GSuite
        from proto.hyperbrowser.StaticFile import GalaxyRunSpecificFile
        from gold.gsuite.GSuiteEditor import selectColumnsFromGSuite
        staticFile=[]
        
        results = []
        for refTrack in refTrackNameList:
            analysisDef = '-> ProportionCountStat' #ProportionCountStat #CountStat
            res = GalaxyInterface.runManual([refTrack], analysisDef, regSpec, binSpec, genome, username=username, galaxyFn=galaxyFn, printRunDescription=False, printResults=False, printProgress=False)
            segCoverageProp = [res[seg]['Result'] for seg in res.getAllRegionKeys()]
            results.append(segCoverageProp)
            
            regFileNamer = GalaxyRunSpecificFile(refTrack, galaxyFn)
            staticFile.append([regFileNamer.getLink('Download bed-file'), regFileNamer.getLoadToHistoryLink('Download bed-file to History')])

        refGSuite = getGSuiteFromGalaxyTN(choices.gsuite)

        if TITLE_COL == choices.selectColumns:
            selected = trackTitles
        else:
            selected = refGSuite.getAttributeValueList(choices.selectColumns)

        yAxisNameOverMouse=[]
        metadataAll =[]

        for x in range(0, len(selected)):
            if selected[x] == None:
                yAxisNameOverMouse.append(str(trackTitles[x]) + ' --- ' + 'None')
            else:
                if TITLE_COL == choices.selectColumns:
                    yAxisNameOverMouse.append(selected[x].replace('\'', '').replace('"', ''))
                else:
                    metadata = str(selected[x].replace('\'', '').replace('"', ''))
                    yAxisNameOverMouse.append(str(trackTitles[x]) + ' --- ' + metadata)
                    metadataAll.append(metadata)

        colorListForYAxisNameOverMouse = []
        if len(metadataAll) > 0:
            import quick.webtools.restricted.visualization.visualizationGraphs as vg
            cList = vg.colorList().fullColorList()
            uniqueCList = list(set(metadataAll))

            for m in metadataAll:
                colorListForYAxisNameOverMouse.append(cList[uniqueCList.index(m)])

        #startEnd - order in res
        startEndInterval = []
        startEnd = []
        i=0
        

        extraX=[]
        rowLabel = []
        for ch in res.getAllRegionKeys():
            rowLabel.append(str(ch.chr) + ":" + str(ch.start) + "-" + str(ch.end) + str(' (Pos)' if ch.strand else ' (Neg)'))
            if not i==0 and not i==len(res.getAllRegionKeys())-1:
                start = ch.start
                if start-end > 0:
                    startEnd.append(start-end)
                else:
                    startEnd.append('null')
                    extraX.append("""{ color: 'orange', width: 5, value: '""" + str(i-0.5) + """' }""")
                startEndInterval.append(ch.end - ch.start)
            else:
                startEndInterval.append(ch.end - ch.start)
            end = ch.end
            i+=1

        extraXAxis='plotLines: [ '
        extraXAxis = extraXAxis + ",".join(extraX)
        extraXAxis = extraXAxis + """ ],  """

        #rowLabel = res.getAllRegionKeys()
        #rowLabel = [str(x) for x in rowLabel]
        

        import quick.webtools.restricted.visualization.visualizationPlots as vp

        htmlCore = HtmlCore()
        htmlCore.begin()
        htmlCore.divBegin(divId='results-page')
        htmlCore.divBegin(divClass='results-section')
        htmlCore.divBegin('plotDiv')
        htmlCore.line(vp.addJSlibs())
        htmlCore.line(vp.useThemePlot())
        htmlCore.line(vp.addJSlibsExport())
        htmlCore.line(vp.axaddJSlibsOverMouseAxisisPopup())
        #vp.addGuideline(htmlCore)
        htmlCore.line(vp._addGuidelineV1())

        htmlCore.line(vp.addJSlibsHeatmap())

        from config.Config import DATA_FILES_PATH

        from proto.StaticFile import StaticFile, GalaxyRunSpecificFile

        #sf = GalaxyRunSpecificFile(['result.txt'], galaxyFn)
        #outFile = sf.getDiskPath(ensurePath=True)

        htmlCore.divBegin()
        writeFile = open(
            cls.makeHistElement(galaxyExt='tabular',
                                title='result'), 'w')
        # htmlCore.link('Get all results', sf.getURL())
        htmlCore.divEnd()

        i = 0

        writeFile.write('Track' + '\t' + '\t'.join(rowLabel)+ '\n')
        for rList in results:
            writeFile.write(str(yAxisNameOverMouse[i]) + '\t' + '\t'.join([str(r) for r in rList]) + '\n')
            i+=1




        fileOutput = GalaxyRunSpecificFile(['heatmap.png'],
                                           galaxyFn)
        ensurePathExists(fileOutput.getDiskPath())

        fileOutputPdf = GalaxyRunSpecificFile(['heatmap.pdf'],
                                              galaxyFn)
        ensurePathExists(fileOutputPdf.getDiskPath())

        cls.generateStaticRPlot(results, colorListForYAxisNameOverMouse, rowLabel, yAxisNameOverMouse,
                                colorMaps[choices.colorMapSelectList],
                                fileOutput.getDiskPath(), fileOutputPdf.getDiskPath())


        htmlCore.divBegin(divId='heatmap', style="padding: 10px 0 px 10 px 0px;margin: 10px 0 px 10 px 0px")
        htmlCore.link('Download heatmap image', fileOutputPdf.getURL())
        htmlCore.divEnd()

        if len(results) * len(results[1]) >= 10000:
            htmlCore.image(fileOutput.getURL())


        else:

            min = 1000000000
            max = -1000000000
            for rList in results:
                for r in rList:
                    if min > r:
                        min = r
                    if max < r:
                        max = r




            if max-min != 0:
                resultNormalised = []
                for rList in results:
                    resultNormalisedPart = []
                    for r in rList:
                        resultNormalisedPart.append((r-min)/(max-min))
                    resultNormalised.append(resultNormalisedPart)

                addText = '(normalised to [0, 1])'
            else:
                resultNormalised = results
                addText = ''


            hm, heatmapPlotNumber, heatmapPlot = vp.drawHeatMap(
                                                    resultNormalised,
                                                    colorMaps[choices.colorMapSelectList],
                                                    label='this.series.xAxis.categories[this.point.x] + ' + "'<br >'" + ' + yAxisNameOverMouse[this.point.y] + ' + "'<br>Overlap proportion" + str(addText) + ": <b>'" + ' + this.point.value + ' + "'</b>'",
                                                    yAxisTitle= 'Reference tracks',
                                                    categories=rowLabel,
                                                    tickInterval=1,
                                                    plotNumber=3,
                                                    interaction=True,
                                                    otherPlotNumber=1,
                                                    titleText='Overlap with reference tracks for each local region',
                                                    otherPlotData=[startEnd, startEndInterval],
                                                    overMouseAxisX=True,
                                                    overMouseAxisY=True,
                                                    yAxisNameOverMouse=yAxisNameOverMouse,
                                                    overMouseLabelY=" + 'Track: '" + ' + this.value + ' + "' '" + ' + yAxisNameOverMouse[this.value] + ',
                                                    overMouseLabelX = ' + this.value.substring(0, 20) +',
                                                    extrOp = staticFile
                                                    )
            htmlCore.line(hm)
            htmlCore.line(vp.drawChartInteractionWithHeatmap(
                [startEndInterval, startEnd],
                tickInterval=1,
                type='line',
                categories=[rowLabel, rowLabel],
                seriesType=['line', 'column'],
                minWidth=300,
                height=500,
                lineWidth=3,
                titleText=['Lengths of segments (local regions)','Gaps between consecutive segments'],
                label=['<b>Length: </b>{point.y}<br/>', '<b>Gap length: </b>{point.y}<br/>'],
                subtitleText=['',''],
                yAxisTitle=['Lengths','Gap lengths'],
                seriesName=['Lengths','Gap lengths'],
                xAxisRotation=90,
                legend=False,
                extraXAxis=extraXAxis,
                heatmapPlot=heatmapPlot,
                heatmapPlotNumber=heatmapPlotNumber,
                overMouseAxisX=True,
                overMouseLabelX = ' + this.value.substring(0, 20) +'
                ))


        htmlCore.divEnd()
        htmlCore.divEnd()
        htmlCore.divEnd()
        htmlCore.end()

        htmlCore.hideToggle(styleClass='debug')

        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.
        '''

        trackTitles, tracks, genome = getGSuiteDataFromGalaxyTN(
            choices.histElement)

        regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices)
        multiTrackAnalysis = None
        if choices.Analysis == cls.LBL_BP_COVERAGE_BPS:
            multiTrackAnalysis = MultiTrackBasePairCoverage(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)

        elif choices.Analysis == cls.LBL_BP_COVERAGE_PROPORTIONAL:
            multiTrackAnalysis = MultiTrackBasePairCoverageProportional(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)
        elif choices.Analysis == cls.LBL_FACTORS_OBSERVED_VS_EXPECTED:
            multiTrackAnalysis = MultiTrackFactorsOfObserevedVsExpectedOverlap(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)
        elif choices.Analysis == cls.LBL_OBSERVED_VS_EXPECTED_GIVEN_BIN_PRESENCE:
            multiTrackAnalysis = MultiTrackExpectedOverlapGivenBinPresence(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)
        elif choices.Analysis == cls.LBL_HYPOTHESIS_TESTING_MULTI:
            randOption = cls._getRandomizationAnalysisOption(choices)
            numResamplingsOption = '[numResamplings=%s]' % choices.NumResamplings
            multiTrackAnalysis = MultiTrackHypothesisTesting(
                tracks,
                trackTitles,
                regSpec,
                binSpec,
                genome,
                galaxyFn,
                randOption=randOption,
                numResamplingsOption=numResamplingsOption)

        elif choices.Analysis == cls.LBL_COVERAGE_DEPTH_BPS:
            multiTrackAnalysis = MultiTrackCoverageDepthBps(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)

        elif choices.Analysis == cls.LBL_COVERAGE_DEPTH_PROPORTIONAL:
            multiTrackAnalysis = MultiTrackCoverageDepthProportional(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)

        elif choices.Analysis == cls.LBL_COVERAGE_DEPTH_PROPORTIONAL_TO_EACHOTHER:
            multiTrackAnalysis = MultiTrackCoverageDepthProportionalToAny(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)

        elif choices.Analysis == cls.LBL_COVERAGE_DEPTH_EXTRA:
            multiTrackAnalysis = MultiTrackCoverageDepthExtra(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)

        elif choices.Analysis == cls.LBL_TRACK_COVERAGE_PROPORTION_TO_OTHERS:
            multiTrackAnalysis = MultiTrackCoverageProportionToOthers(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)

        elif choices.Analysis == cls.LBL_INCLUSION_STRUCTURE:
            multiTrackAnalysis = MultiTrackInclusionStructure(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)

        elif choices.Analysis == cls.LBL_FOCUSED_TRACK_DEPTH_COVERAGE:
            multiTrackAnalysis = MultiTrackFocusedTrackDepthCoverage(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)

        elif choices.Analysis == cls.LBL_FOCUSED_TRACK_DEPTH_COVERAGE_PROPORTIONAL:
            multiTrackAnalysis = MultiTrackFocusedTrackDepthCoverageProportional(
                tracks, trackTitles, regSpec, binSpec, genome, galaxyFn)
        else:
            raise Exception(repr(choices.Analysis))
        multiTrackAnalysis.execute(printHtmlBeginEnd=False)