def execute(cls, choices, galaxyFn=None, username=''): cls._setDebugModeIfSelected(choices) gSuite = getGSuiteFromGalaxyTN(choices.gsuite) if gSuite.genome != choices.genome: gSuite.setGenomeOfAllTracks(choices.genome) regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) paragraphs = [] paragraphs += generatePilotPageTwoParagraphs(gSuite, galaxyFn, regSpec=regSpec, binSpec=binSpec) paragraphs += generatePilotPageThreeParagraphs(gSuite, galaxyFn, regSpec=regSpec, binSpec=binSpec) core = HtmlCore() core.begin() core.divBegin(divId='results-page') core.divBegin(divClass='results-section') core.header('Similarity and uniqueness of tracks') for prg in paragraphs: core.paragraph(prg) core.divEnd() core.divEnd() core.end() print 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. ''' gSuite = getGSuiteFromGalaxyTN(choices.gSuite) regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) analysisBins = GalaxyInterface._getUserBinSource(regSpec, binSpec, genome=gSuite.genome) gSuiteOverview = GSuiteOverview(gSuite) coreHtml = HtmlCore() coreHtml.begin() coreHtml.append( str( getGSuiteOverviewHtmlCore( gSuiteOverview.getGSuiteOverviewData( analysisBins=analysisBins)))) coreHtml.end() print coreHtml
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) trackTitles, trackNames, genome, firstCollectionTrackNr = cls._getTrackData( choices) regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) multiTrackAnalysis = MultiTrackAnalysis( trackNames, trackTitles, regSpec, binSpec, genome, galaxyFn, analysisDef=cls._createAnalysisDef(choices)) multiTrackAnalysis.execute(printTrackNamesTable=False)
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. ''' regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) genome = choices.Genome #trackNames = [choices[choiceIndex].split(':') for choiceIndex in [2,4,6]] #trackNames = [x.split(':') for x in [choices.Track1, choices.Track2, choices.Track3]] trackNames = cls.getAllChosenTracks(choices) print trackNames #for tnIndex, choiceIndex in zip(range(3),[2,4,6]): # tn = choices[choiceIndex].split(':') # trackNames[tnIndex] = tn #trackNames[tnIndex] = ExternalTrackManager.getPreProcessedTrackFromGalaxyTN(genome, tn) \ # if ExternalTrackManager.isGalaxyTrack(tn) \ # else tn #analysisDef = 'dummy [trackNameIntensity=%s]-> ThreeWayBpOverlapStat' % '|'.join(trackNames[2]) #Do not preserve any pair-wise relations', 'Preserve pair-wise relation between Track 1 and Track 3', 'Preserve pair-wise relation between Track 2 and Track 3'] #['Base pair coverage of all track combinations', 'Inclusion structure between tracks', 'Observed versus expected overlap with various relations preserved', 'Hypothesis testing on multi-track relations'] if choices.Analysis == 'Base pair coverage of all track combinations': analysisDef = 'dummy -> ThreeWayBpOverlapStat' elif choices.Analysis == 'Inclusion structure between tracks': analysisDef = 'dummy -> ThreeWayTrackInclusionBpOverlapStat' elif choices.Analysis == 'Observed versus expected overlap with various relations preserved': pass elif choices.Analysis == 'Factors of observed versus expected overlap with various relations preserved': analysisDef = 'Dummy [rawStatistic=ThreeWayExpectedWithEachPreserveCombinationBpOverlapStat] [referenceResDictKey=preserveNone] -> GenericFactorsAgainstReferenceResDictKeyStat' elif choices.Analysis == 'Hypothesis testing on multi-track relations': randOption = cls._getRandomizationAnalysisOption(choices) numResamplingsOption = '[numResamplings=%s]' % choices.NumResamplings #assert len(trackNames) == 3, trackNames #currently, due to ThreeTrackBpsCoveredByAllTracksStat #analysisDef = 'dummy [tail=different] [rawStatistic=ThreeTrackBpsCoveredByAllTracksStat] %s %s -> RandomizationManagerStat' % (randOption, numResamplingsOption) resDictKey = '1' * (len(trackNames)) analysisDef = 'dummy [tail=different] [rawStatistic=SingleValExtractorStat] [childClass=ThreeWayBpOverlapStat] [resultKey=%s] %s %s -> RandomizationManagerStat' % ( resDictKey, randOption, numResamplingsOption) print analysisDef elif choices.Analysis == 'Coverage depth of multiple tracks along the genome': analysisDef = 'dummy -> ThreeWayCoverageDepthStat' else: raise Exception(choices.Analysis) analysisDef = 'dummy [extraTracks=%s] ' % '&'.join( ['|'.join(tn) for tn in trackNames[2:]]) + analysisDef #GalaxyInterface.run(trackNames[0], trackNames[1], analysisDef, regSpec, binSpec, genome, galaxyFn, trackNames[2], printRunDescription=False) GalaxyInterface.run(trackNames[0], trackNames[1], analysisDef, regSpec, binSpec, genome, galaxyFn, printRunDescription=False)
def execute(choices, galaxyFn=None, username=''): gSuite = getGSuiteFromGalaxyTN(choices.gsuite) if gSuite.genome != choices.genome: gSuite.setGenomeOfAllTracks(choices.genome) regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) paragraphs = generatePilotPageTwoParagraphs(gSuite, galaxyFn, regSpec=regSpec, binSpec=binSpec) core = HtmlCore() core.begin() core.header('Overlap between tracks') for prg in paragraphs: core.paragraph(prg) core.end() print core
def execute(choices, galaxyFn=None, username=''): gSuite = getGSuiteFromGalaxyTN(choices.gsuite) if gSuite.genome != choices.genome: gSuite.setGenomeOfAllTracks(choices.genome) regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) paragraphs = OrderedDict() paragraphs[ 'Basic overview of tracks in collection'] = generatePilotPageOneParagraphs( gSuite, galaxyFn, regSpec=regSpec, binSpec=binSpec, username=username) paragraphs['Overlap between tracks'] = generatePilotPageTwoParagraphs( gSuite, galaxyFn, regSpec=regSpec, binSpec=binSpec) paragraphs[ 'Similarity and uniqueness of tracks'] = generatePilotPageThreeParagraphs( gSuite, galaxyFn, regSpec=regSpec, binSpec=binSpec) paragraphs['Clustering of tracks'] = generatePilotPageFiveParagraphs( gSuite, galaxyFn) core = HtmlCore() core.begin() core.divBegin(divId='results-page', divClass='trackbook_main') for hdr, prgList in paragraphs.iteritems(): core.divBegin(divClass='trackbook_section') core.divBegin(divClass='results-section') core.header(hdr) for prg in prgList: core.paragraph(prg) core.divEnd() core.divEnd() core.divEnd() core.end() print core
def execute(cls, choices, galaxyFn=None, username=''): gSuite = getGSuiteFromGalaxyTN(choices.gsuite) if gSuite.genome != choices.genome: gSuite.setGenomeOfAllTracks(choices.genome) regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) paragraphs = generatePilotPageOneParagraphs(gSuite, galaxyFn, regSpec=regSpec, binSpec=binSpec, username=username) core = HtmlCore() core.begin() core.divBegin(divId='results-page') core.divBegin(divClass='results-section') core.header('Basic overview of tracks in collection') for prg in paragraphs: core.paragraph(prg) core.divEnd() core.divEnd() core.end() print core
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=''): cls._setDebugModeIfSelected(choices) genome = choices.genome genomicRegions = choices.genomicRegions genomicRegionsTracks = choices.genomicRegionsTracks sourceTfs = choices.sourceTfs sourceTfsDetails = choices.sourceTfsDetails tfTracks = choices.tfTracks # Get Genomic Region track name: if genomicRegions == cls.REGIONS_FROM_HISTORY: galaxyTN = genomicRegionsTracks.split(':') genElementTrackName = ExternalTrackManager.getPreProcessedTrackFromGalaxyTN( genome, galaxyTN) #queryGSuite = getGSuiteFromGalaxyTN(genomicRegionsTracks) #queryTrackList = [Track(x.trackName, x.title) for x in queryGSuite.allTracks()] elif genomicRegions == 'Hyperbrowser repository': selectedGenRegTrack = TfbsTrackNameMappings.getTfbsTrackNameMappings( genome)[genomicRegionsTracks] if isinstance(selectedGenRegTrack, dict): genElementTrackName = selectedGenRegTrack.values() else: genElementTrackName = selectedGenRegTrack elif genomicRegions == 'Hyperbrowser repository (cell-type-specific)': genElementTrackName = ['Private', 'Antonio' ] + genomicRegionsTracks.split(':') else: return # Get TF track names: if isinstance(tfTracks, dict): selectedTfTracks = [ key for key, val in tfTracks.iteritems() if val == 'True' ] else: selectedTfTracks = [tfTracks] queryTrackTitle = '--'.join(genElementTrackName) trackTitles = [queryTrackTitle] tracks = [Track(genElementTrackName, trackTitle=queryTrackTitle)] for i in selectedTfTracks: if sourceTfs == 'Hyperbrowser repository': tfTrackName = TfTrackNameMappings.getTfTrackNameMappings( genome)[sourceTfsDetails] + [i] tracks.append( Track(tfTrackName, trackTitle=tfTrackName[len(tfTrackName) - 1])) trackTitles.append(tfTrackName[len(tfTrackName) - 1]) else: tfTrackName = i.split(':') queryGSuite = getGSuiteFromGalaxyTN(sourceTfsDetails) for x in queryGSuite.allTracks(): selectedTrackNames = (':'.join(x.trackName)) if i == selectedTrackNames: tracks.append(Track(x.trackName, x.title)) trackTitles.append(x.trackName[-1]) # queryGSuite = getGSuiteFromGalaxyTN(sourceTfsDetails) # tfTrackName = [x.trackName for x in queryGSuite.allTracks()] + [i] # tracks += [Track(x.trackName, x.title) for x in queryGSuite.allTracks()] # trackTitles += tfTrackName # print tfTrackName # print tracks # print trackTitles trackTitlesForStat = trackTitles trackTitles = CommonConstants.TRACK_TITLES_SEPARATOR.join(trackTitles) ##first statistic for Q2 resultsForStatistics = OrderedDict() similarityFunc = [ #GSuiteStatUtils.T7_RATIO_OF_OBSERVED_TO_EXPECTED_OVERLAP, GSuiteStatUtils.T5_RATIO_OF_OBSERVED_TO_EXPECTED_OVERLAP ] for similarityStatClassName in similarityFunc: regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) analysisBins = GalaxyInterface._getUserBinSource(regSpec, binSpec, genome=genome) mcfdrDepth = AnalysisDefHandler( REPLACE_TEMPLATES['$MCFDR$']).getOptionsAsText().values()[0][0] analysisDefString = REPLACE_TEMPLATES[ '$MCFDR$'] + ' -> GSuiteSimilarityToQueryTrackRankingsAndPValuesWrapperStat' analysisSpec = AnalysisDefHandler(analysisDefString) analysisSpec.setChoice('MCFDR sampling depth', mcfdrDepth) analysisSpec.addParameter('assumptions', 'PermutedSegsAndIntersegsTrack_') analysisSpec.addParameter( 'rawStatistic', GSuiteStatUtils. PAIRWISE_STAT_LABEL_TO_CLASS_MAPPING[similarityStatClassName]) analysisSpec.addParameter( 'pairwiseStatistic', GSuiteStatUtils. PAIRWISE_STAT_LABEL_TO_CLASS_MAPPING[similarityStatClassName] ) #needed for call of non randomized stat for assertion analysisSpec.addParameter('tail', 'more') analysisSpec.addParameter('trackTitles', trackTitles) #that need to be string analysisSpec.addParameter('queryTracksNum', str(len(tracks))) results = doAnalysis(analysisSpec, analysisBins, tracks).getGlobalResult() if not similarityStatClassName in resultsForStatistics: resultsForStatistics[similarityStatClassName] = {} resultsForStatistics[similarityStatClassName] = results keyTitle = [ #'Normalized ratio of observed to expected overlap (normalized Forbes similarity measure)', 'Ratio of observed to expected overlap (Forbes similarity measure)' ] # 'Normalized Forbes coefficient: ratio of observed to expected overlap normalized in relation to the reference GSuite', # 'Forbes coefficient: ratio of observed to expected overlap' keyTitle = [ #GSuiteStatUtils.T7_RATIO_OF_OBSERVED_TO_EXPECTED_OVERLAP, GSuiteStatUtils.T5_RATIO_OF_OBSERVED_TO_EXPECTED_OVERLAP ] resultDict = AllTfsOfRegions.countStatistics(similarityFunc, choices, genome, tracks, trackTitlesForStat) resultDictShow = AllTfsOfRegions.countStatisticResults( resultDict, keyTitle, trackTitlesForStat) # print resultsForStatistics '''selectedTrackNames = [] if sourceTfs == 'History (user-defined)': if selectedTfTracks.split(":")[1] == "gsuite": gSuite = getGSuiteFromGalaxyTN(selectedTfTracks) for track in gSuite.allTracks(): selectedTrackNames.append(track.trackName) else: galaxyTN = selectedTfTracks.split(':') gRegTrackName = ExternalTrackManager.getPreProcessedTrackFromGalaxyTN(genome, galaxyTN) selectedTrackNames.append(gRegTrackName) else:''' tfNameList = [] #Intersection between TF Tracks and selected region (Table 1): n = 0 allTargetBins = [] alltfNames = [] table1 = [] for i in selectedTfTracks: n = n + 1 #newGalaxyFn = galaxyFn.split(".")[0] + str(n) + "." + "dat" if sourceTfs == 'Hyperbrowser repository': tfTrackName = TfTrackNameMappings.getTfTrackNameMappings( genome)[sourceTfsDetails] + [i] else: tfTrackName = i.split(':') tfTrackName.pop(0) #tfIntersection.expandReferenceTrack(upFlankSize, downFlankSize) tfIntersection = TrackIntersection(genome, genElementTrackName, tfTrackName, galaxyFn, str(n)) regFileNamer = tfIntersection.getIntersectedRegionsStaticFileWithContent( ) targetBins = tfIntersection.getIntersectedReferenceBins() #regSpec, targetBins = UserBinSelector.getRegsAndBinsSpec(choices) tfHits = [i] * len(targetBins) fixedTargetBins = [str(a).split(" ")[0] for a in targetBins] extendedTargetBins = [ list(a) for a in zip(fixedTargetBins, tfHits) ] allTargetBins = allTargetBins + extendedTargetBins tfName = i alltfNames = alltfNames + [tfName] # Save output table: tfNameList.append(tfName) line = [tfName] + [len(targetBins)] + [ regFileNamer.getLink('Download bed-file') ] + [ regFileNamer.getLoadToHistoryLink('Send bed-file to History') ] table1 = table1 + [line] # Computing totals: fullCase = ','.join(alltfNames) firstColumn = [item[0] for item in allTargetBins] uniqueAllTargetBins = list(set(firstColumn)) # Group TFs by bound region: d1 = defaultdict(list) for k, v in allTargetBins: d1[k].append(v) allTFTargetBins = dict((k, ','.join(v)) for k, v in d1.iteritems()) allTFTargetList = [] fullCaseTFTargetList = [] for key, value in allTFTargetBins.iteritems(): allTFTargetList = allTFTargetList + [[key, value]] if value == fullCase: fullCaseTFTargetList = fullCaseTFTargetList + [[key, value]] analysis3 = TrackIntersection.getFileFromTargetBins( allTFTargetList, galaxyFn, str(3)) analysis4 = TrackIntersection.getFileFromTargetBins( fullCaseTFTargetList, galaxyFn, str(4)) # Print output to table: title = 'TF targets and co-occupancy of ' + genElementTrackName[ -1] + ' genomic regions' htmlCore = HtmlCore() pf = plotFunction(tableId='resultsTable') htmlCore.begin() htmlCore.header(title) htmlCore.divBegin('resultsDiv') htmlCore.line(pf.createButton(bText='Show/Hide more results')) # htmlCore.tableHeader(['Transcription Factor', 'Normalized ratio of observed to expected overlap (normalized Forbes similarity measure) -- Similarity to genomic regions track', 'Normalized ratio of observed to expected overlap (normalized Forbes similarity measure) -- p-value','Ratio of observed to expected overlap (Forbes similarity measure) -- Similarity to genomic regions track', 'Ratio of observed to expected overlap (Forbes similarity measure) -- p-value', 'Number of TF-Target Track Regions', 'File of TF Target Regions', 'File of TF Target Regions', 'Number of TF-co-occupied Regions', 'File of TF co-occupied Regions', 'File of TF co-occupied Regions', 'Rank of TF co-occupancy motifs', 'Rank of TF co-occupancy motifs'], sortable=True, tableId='resultsTable') #previous ordering # htmlCore.tableHeader(['Transcription Factor', 'Normalized Forbes index --overlap score', # 'Normalized Forbes index --p-value', # 'Forbes index --overlap score', 'Forbes index --p-value', # 'Number of TF-Target Track Regions', 'File of TF Target Regions', # 'File of TF Target Regions', 'Number of target track regions occupied by this TF', # 'File of TF co-occupied Regions', 'File of TF co-occupied Regions', # 'Rank of TF co-occupancy motifs', 'Rank of TF co-occupancy motifs'], # sortable=True, tableId='resultsTable') htmlCore.tableHeader( [ 'Transcription Factor', 'Number of TF-Target Track Regions', 'File of TF Track Regions', 'Number of target track regions occupied by this TF', 'File of TF Target Regions', 'Forbes index --overlap score', 'Forbes index --p-value', #'Normalized Forbes index --overlap score', 'Normalized Forbes index --p-value', 'File of TF co-occupied Regions', 'Rank of TF co-occupancy motifs' ], sortable=True, tableId='resultsTable') # Adding co-occupancy results to table: n = 1000 genRegionNumElements = [ int(x) for x in getTrackRelevantInfo.getNumberElements( genome, genElementTrackName) ] for key0, it0 in resultsForStatistics.iteritems(): for el in tfNameList: if el not in it0: resultsForStatistics[key0][el] = [None, None] resultsPlotDict = {} resultPlotCat = [] resultsPlot = [] resultsForStatisticsProper = {} for key0, it0 in resultsForStatistics.iteritems(): if not key0 in resultsPlotDict: resultsPlotDict[key0] = {} resultsPlotPart = [] for key1, it1 in it0.iteritems(): resultsPlotPart.append(it1[0]) if not key1 in resultsForStatisticsProper: resultsForStatisticsProper[key1] = [] if not key1 in resultsPlotDict[key0]: resultsPlotDict[key0][key1] = None for el in it1: resultsForStatisticsProper[key1].append(el) resultsPlotDict[key0][key1] = it1[0] resultPlotCat.append(tfNameList) resultPlotCat.append(tfNameList) #resultPlotCatPart = tfNameList # print resultPlotCatPart for key0, it0 in resultsPlotDict.iteritems(): resultsPlotPart = [] for el in tfNameList: if el in it0: resultsPlotPart.append(it0[el]) else: resultsPlotPart.append(None) resultsPlot.append(resultsPlotPart) for i in table1: thisCaseTFTargetList = [] for key, value in allTFTargetList: if i[0] in value and ',' in value: thisCaseTFTargetList = thisCaseTFTargetList + [[ key, value ]] n = n + 1 thisAnalysis = TrackIntersection.getFileFromTargetBins( thisCaseTFTargetList, galaxyFn, str(n)) thisCaseCoCountsList = [] thing = [x[1] for x in thisCaseTFTargetList] for k in list(set(thing)): thisCount = thing.count(k) thisCaseCoCountsList = thisCaseCoCountsList + \ [[k, thisCount, 100*float(thisCount)/float(sum(genRegionNumElements)), 100*float(thisCount)/float(len(thisCaseTFTargetList))]] thisCaseCoCountsList.sort(key=lambda x: x[2], reverse=True) n = n + 1 thisCoCountsAnalysis = TrackIntersection.getOccupancySummaryFile( thisCaseCoCountsList, galaxyFn, str(n)) thisLine = [len(thisCaseTFTargetList)] + \ [thisAnalysis.getLink('Download file')] + [thisAnalysis.getLoadToHistoryLink('Send file to History')] + \ [thisCoCountsAnalysis.getLink('Download file')] + [thisCoCountsAnalysis.getLoadToHistoryLink('Send file to History')] newLineI = [] tfName = i[0] newLineI.append(tfName) for el in resultsForStatisticsProper[tfName]: newLineI.append(el) for elN in range(1, len(i)): newLineI.append(i[elN]) # htmlCore.tableLine(i + thisLine) # htmlCore.tableHeader(['Transcription Factor', 'Normalized Forbes index --overlap score', # 'Normalized Forbes index --p-value', # 'Forbes index --overlap score', 'Forbes index --p-value', # 'Number of TF-Target Track Regions', 'File of TF Target Regions', # 'File of TF Target Regions', 'Number of target track regions occupied by this TF', # 'File of TF co-occupied Regions', 'File of TF co-occupied Regions', # 'Rank of TF co-occupancy motifs', 'Rank of TF co-occupancy motifs'], # sortable=True, tableId='resultsTable') # htmlCore.tableHeader(['Transcription Factor', 'Number of TF-Target Track Regions', 'File of TF Track Regions', # 'Number of target track regions occupied by this TF', 'File of TF Target Regions', # 'Forbes index --overlap score', 'Forbes index --p-value', # 'Normalized Forbes index --overlap score', 'Normalized Forbes index --p-value', # 'File of TF co-occupied Regions', 'Rank of TF co-occupancy motifs'], # sortable=True, tableId='resultsTable') tl = newLineI + thisLine # previous ordering tl - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 # actual ordering - 0, 5, 7, 8, 7, 3, 4, 1, 2, 9, 11 #ordering = [0, 5, 7, 8, 10, 3, 4, 1, 2, 10, 12] ordering = [0, 3, 5, 6, 8, 1, 2, 8, 10] #1, 2, => delete eoList = [] for eo in ordering: eoList.append(tl[eo]) htmlCore.tableLine(eoList) totalCoOccupancyTargetList = [] n = 2000 for key, value in allTFTargetList: n = n + 1 if ',' in value: totalCoOccupancyTargetList = totalCoOccupancyTargetList + [[ key, value ]] #newGalaxyFn = galaxyFn.split(".")[0] + str(n) + "." + "dat" totalCoOccupancyAnalysis = TrackIntersection.getFileFromTargetBins( totalCoOccupancyTargetList, galaxyFn, str(n)) #line = ['Total reported regions'] + [len(allTargetBins)] + [''] + [''] + [''] + [''] + [''] #line = ['Full co-occupancy of ' + fullCase] + ['-'] + ['-'] + ['-'] + ['-'] + ['-'] + ['-'] + ['-'] + [len(fullCaseTFTargetList)] + [analysis4.getLink('Download file')] + [analysis4.getLoadToHistoryLink('Send file to History')] + ['-'] + ['-'] line = ['Full co-occupancy of ' + fullCase] + \ ['-'] + \ ['-'] + \ [len(fullCaseTFTargetList)] + \ ['-'] + \ ['-'] + \ ['-'] + \ [analysis4.getLoadToHistoryLink('Send file to History')] + \ ['-'] htmlCore.tableLine(line) #line = ['Total unique regions'] + ['-'] + ['-'] + ['-'] + ['-'] + [len(allTFTargetList)] + [analysis3.getLink('Download bed-file')] + [analysis3.getLoadToHistoryLink('Send bed-file to History')] + [len(totalCoOccupancyTargetList)] + [totalCoOccupancyAnalysis.getLink('Download file')] + [totalCoOccupancyAnalysis.getLoadToHistoryLink('Send file to History')] + ['-'] + ['-'] line = ['Total unique regions'] + \ [len(allTFTargetList)] + \ ['-'] + \ [len(totalCoOccupancyTargetList)] + \ [analysis3.getLoadToHistoryLink('Send bed-file to History')] + \ ['-'] +\ ['-'] + \ [totalCoOccupancyAnalysis.getLoadToHistoryLink('Send file to History')] + \ ['-'] htmlCore.tableLine(line) htmlCore.tableFooter() htmlCore.divEnd() # htmlCore.line(pf.hideColumns(indexList=[2, 4])) # sumRes = 0 for r in resultsPlot[0]: if r != None: sumRes += r if sumRes != 0: vg = visualizationGraphs() result = vg.drawColumnCharts( [resultsPlot[0]], height=300, categories=resultPlotCat, legend=False, addOptions='width: 90%; float:left; margin: 0 4%;', #titleText=['Overlap between TFs and genomic region using normalized Forbes', 'Overlap between TFs and genomic region using Forbes'], titleText=[ 'Overlap between TFs and genomic region using Forbes' ], xAxisRotation=90, xAxisTitle='TF', yAxisTitle='value') htmlCore.line(result) for key0, it0 in resultDictShow.iteritems(): htmlCore.divBegin('resultsDiv' + str(key0)) htmlCore.header(key0) htmlCore.tableHeader(it0[0], sortable=True, tableId='resultsTable' + str(key0)) for elN in range(1, len(it0)): htmlCore.tableLine(it0[elN]) htmlCore.tableFooter() htmlCore.divEnd() htmlCore.hideToggle(styleClass='debug') htmlCore.end() print htmlCore
def makeAnalysis(cls, gSuite1, gSuite2, columnsForStat, galaxyFn, choices): genomeType = 'single' #if True then none of column in both gsuite are equal then for example, for gSUite 2 dim and 3 dim we have 5 dim # in the other case (when some columns are equal we have 4 dim) checkWhichDimension = True for el in columnsForStat: if el == 0: checkWhichDimension=False break if choices.type == 'basic': stat = choices.statistic statIndex = CountStatisticForCombinationsFromTwoLevelSuites.STAT_LIST_INDEX statIndex = statIndex.index(stat) else: stat= '0' statIndex = 0 if choices.intraOverlap == CountStatisticForCombinationsFromTwoLevelSuites.MERGE_INTRA_OVERLAPS: analysisDef = 'dummy -> RawOverlapStat' else: analysisDef = 'dummy [withOverlaps=yes] -> RawOverlapAllowSingleTrackOverlapsStat' regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) listResults = [] for el1 in gSuite1: for el2 in gSuite2: if genomeType == 'single': listPartResults=[] if (checkWhichDimension == True and el1[columnsForStat[0]] == el2[columnsForStat[1]]) or (checkWhichDimension == False): gSuite1Path = el1[0]#path for track1 gSuite2Path = el2[0]#path for track2 #print [gSuite1Path, gSuite2Path] result = GalaxyInterface.runManual([gSuite1Path, gSuite2Path], analysisDef, regSpec, binSpec, choices.genome, galaxyFn, printRunDescription=False, printResults=False) #print str(result) + '<br \>' #print str(processResult(result.getGlobalResult())) + '<br \>' resVal = processResult(result.getGlobalResult())[statIndex] else: resVal = 0 if checkWhichDimension == False: listPartResults = el1[1:] + el2[1:] + [resVal] else: shorterEl2=[] for eN in range(0, len(el2[1:])): if el2[1:][eN] != el2[columnsForStat[1]]: shorterEl2.append(el2[1:][eN]) #listPartResults = el1[1:] + shorterEl2 + [resVal] listPartResults = el1[1:] + el2[1:] + [resVal] listResults.append(listPartResults) if genomeType == 'multi': #count only values with the same genome pass return listResults
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) gSuite = getGSuiteFromGalaxyTN(choices.gSuite) genome = gSuite.genome trackTitles = list(gSuite.allTrackTitles()) tracks = [track.trackName for track in gSuite.allTracks()] refTracks = [] if choices.gSuiteRef: gSuiteRef = getGSuiteFromGalaxyTN(choices.gSuiteRef) refTracks = [track.trackName for track in gSuiteRef.allTracks()] refTracksReady = [':'.join(refTrack) for refTrack in refTracks] regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) clusterMethod = choices.clusteringMethod extra_option = choices.clusteringAlgorithm distanceType = None if clusterMethod == cls.CLUS_METHOD_HIERARCHICAL: distanceType = choices.clusteringOption kmeans_alg = None if clusterMethod == cls.CLUS_METHOD_K_MEANS: kmeans_alg = choices.clusteringAlgorithm extra_option = choices.clusteringOption numreferencetracks = len(refTracks) # if self.params.get('clusterCase') == 'use pair distance': if choices.similarityTech == cls.SIMILARITY_DIRECT_SEQ_LVL: feature = None extra_feature = None if choices.pairDistOption == cls.PAIR_DIST_RATIO_INTERSECT_UNION_MINUS: feature = cls.PAIR_DIST_RATIO_INTERSECT_UNION extra_feature = cls.ONE_MINUS_RATIO elif choices.pairDistOption == cls.PAIR_DIST_RATIO_INTERSECT_UNION_OVER: feature = cls.PAIR_DIST_RATIO_INTERSECT_UNION extra_feature = cls.ONE_OVER_RATIO elif choices.pairDistOption == cls.PAIR_DIST_PAIRWISE_OVERLAP: feature = cls.PAIR_DIST_PAIRWISE_OVERLAP ClusteringExecution.executePairDistance(genome, tracks, trackTitles, clusterMethod, extra_option, feature, extra_feature, galaxyFn, regSpec, binSpec) # elif self.params.get('clusterCase') == 'use refTracks': elif choices.similarityTech == cls.SIMILARITY_RELATIONS_TO_OTHER: refTrackFeatures = [choices.featureSelection] * numreferencetracks ClusteringExecution.executeReferenceTrack( genome, tracks, trackTitles, clusterMethod, extra_option, distanceType, kmeans_alg, galaxyFn, regSpec, binSpec, numreferencetracks, refTracksReady, refTrackFeatures) # elif self.params.get('clusterCase') == 'self feature': #self feature case. elif choices.similarityTech == cls.SIMILARITY_POSITIONAL: #self feature case. feature = choices.featureSelection ClusteringExecution.executeSelfFeature(genome, tracks, trackTitles, clusterMethod, extra_option, feature, distanceType, kmeans_alg, galaxyFn, regSpec, binSpec) else: # regions clustering case # self.handleRegionClustering(genome, tracks, clusterMethod, extra_option) #TODO: handle region clustering pass
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
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. :param choices: Dict holding all current selections :param galaxyFn: :param username: """ cls._setDebugModeIfSelected(choices) genome = choices.genome queryTrackNameAsList = ExternalTrackManager.getPreProcessedTrackFromGalaxyTN(genome, choices.queryTrack, printErrors=False, printProgress=False) if choices.intensityTrack: intensityTrackNameAsList = ExternalTrackManager.getPreProcessedTrackFromGalaxyTN(genome, choices.intensityTrack, printErrors=False, printProgress=False) else: intensityTrackNameAsList = None analysisQuestion = choices.analysisQName similarityStatClassName = 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' if analysisQuestion in [cls.Q2, cls.Q3]: randStrat = 'PermutedSegsAndIntersegsTrack_' if choices.isBasic else GSuiteStatUtils.PAIRWISE_RAND_CLS_MAPPING[choices.randStrat] gsuite = getGSuiteFromGalaxyTN(choices.gsuite) regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) analysisBins = GalaxyInterface._getUserBinSource(regSpec, binSpec, genome=genome) queryTrack = Track(queryTrackNameAsList) tracks = [queryTrack] + [Track(x.trackName, trackTitle=x.title) for x in gsuite.allTracks()] queryTrackTitle = prettyPrintTrackName(queryTrack.trackName).replace('/', '_') trackTitles = CommonConstants.TRACK_TITLES_SEPARATOR.join( [quote(queryTrackTitle)] + [quote(x.title, safe='') for x in gsuite.allTracks()]) additionalResultsDict = OrderedDict() additionalAttributesDict = OrderedDict() if analysisQuestion in [cls.Q1, cls.Q2]: additionalAttributesDict = cls.getSelectedAttributesForEachTrackDict(choices.additionalAttributes, gsuite) # additional analysis stats = [SingleValueOverlapStat, CountStat, CountElementStat] # + [CountSegmentsOverlappingWithT2Stat] #takes long time additionalResultsDict = runMultipleSingleValStatsOnTracks(gsuite, stats, analysisBins, queryTrack=queryTrack) core = HtmlCore() if analysisQuestion == cls.Q1: analysisSpec = cls.prepareQ1(reverse, similarityStatClassName, trackTitles) results = doAnalysis(analysisSpec, analysisBins, tracks).getGlobalResult() gsPerTrackResultsModel = GSuitePerTrackResultModel(results, ['Similarity to query track'], additionalResultsDict=additionalResultsDict, additionalAttributesDict=additionalAttributesDict) if choices.leadAttribute and choices.leadAttribute != GSuiteConstants.TITLE_COL: gsPerTrackResults = gsPerTrackResultsModel.generateColumnTitlesAndResultsDict(choices.leadAttribute) else: gsPerTrackResults = gsPerTrackResultsModel.generateColumnTitlesAndResultsDict() core = cls.generateQ1output(additionalResultsDict, analysisQuestion, choices, galaxyFn, gsPerTrackResults, queryTrackTitle, gsuite, results, similarityStatClassName) elif analysisQuestion == cls.Q2: analysisSpec = cls.prepareQ2(choices, similarityStatClassName, trackTitles, randStrat, intensityTrackNameAsList) results = doAnalysis(analysisSpec, analysisBins, tracks).getGlobalResult() core = cls.generateQ2Output(additionalAttributesDict, additionalResultsDict, analysisQuestion, choices, galaxyFn, queryTrackTitle, gsuite, results, similarityStatClassName) else: # Q3 analysisSpec = cls.prepareQ3(choices, similarityStatClassName, summaryFunc, randStrat) results = doAnalysis(analysisSpec, analysisBins, tracks).getGlobalResult() core = cls.generateQ3output(analysisQuestion, queryTrackTitle, results, similarityStatClassName) print str(core)
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)
def execute(cls, choices, galaxyFn=None, username=''): cls._setDebugModeIfSelected(choices) targetGSuite = getGSuiteFromGalaxyTN(choices.gSuiteFirst) refGSuite = getGSuiteFromGalaxyTN(choices.gSuiteSecond) regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) analysisDef = 'dummy -> RawOverlapStat' # analysisDef = 'dummy [withOverlaps=yes] -> RawOverlapAllowSingleTrackOverlapsStat' results = OrderedDict() for targetTrack in targetGSuite.allTracks(): targetTrackName = targetTrack.title for refTrack in refGSuite.allTracks(): refTrackName = refTrack.title if targetTrack.trackName == refTrack.trackName: # print targetTrack.title # print targetTrack.trackName result = DetermineSuiteTracksCoincidingWithAnotherSuite.handleSameTrack( targetTrack.trackName, regSpec, binSpec, targetGSuite.genome, galaxyFn) else: result = GalaxyInterface.runManual( [targetTrack.trackName, refTrack.trackName], analysisDef, regSpec, binSpec, targetGSuite.genome, galaxyFn, printRunDescription=False, printResults=False, printProgress=False).getGlobalResult() if targetTrackName not in results: results[targetTrackName] = OrderedDict() results[targetTrackName][refTrackName] = result stat = STAT_OVERLAP_COUNT_BPS statIndex = STAT_LIST_INDEX[stat] title = '' 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) outputTable = {} for elN in range(0, len(headerColumn)): outputTable[elN] = {} outputTable[elN]['id'] = headerColumn[elN] transposedProcessedResults = [list(x) for x in zip(*processedResults)] # second question sumSecondgSuite # first question numSecondgSuite # fifth question numSecondgSuitePercentage for i in range(0, len(transposedProcessedResults)): outputTable[i]['sumSecondgSuite'] = sum( transposedProcessedResults[i]) if not 'numSecondgSuite' in outputTable[i]: outputTable[i]['numSecondgSuite'] = 0 for j in range(0, len(transposedProcessedResults[i])): if transposedProcessedResults[i][j] >= 1: outputTable[i]['numSecondgSuite'] += 1 else: outputTable[i]['numSecondgSuite'] += 0 outputTable[i]['numSecondgSuitePercentage'] = float( outputTable[i]['numSecondgSuite']) / float( targetGSuite.numTracks()) * 100 from gold.statistic.CountSegmentStat import CountSegmentStat from gold.statistic.CountPointStat import CountPointStat from gold.description.TrackInfo import TrackInfo from gold.statistic.CountStat import CountStat # third question numPairBpSecondgSuite # fourth question numFreqBpSecondgSuite i = 0 for refTrack in refGSuite.allTracks(): formatName = TrackInfo(refTrack.genome, refTrack.trackName).trackFormatName analysisDef = CountStat analysisBins = GalaxyInterface._getUserBinSource( regSpec, binSpec, refTrack.genome) results = doAnalysis(AnalysisSpec(analysisDef), analysisBins, [PlainTrack(refTrack.trackName)]) resultDict = results.getGlobalResult() if len(resultDict) == 0: outputTable[i]['numPairBpSecondgSuite'] = None outputTable[i]['numFreqBpSecondgSuite'] = None outputTable[i]['numFreqUniqueBpSecondgSuite'] = None else: outputTable[i]['numPairBpSecondgSuite'] = resultDict['Result'] if outputTable[i]['numPairBpSecondgSuite'] != 0: outputTable[i]['numFreqBpSecondgSuite'] = float( outputTable[i]['sumSecondgSuite']) / float( outputTable[i]['numPairBpSecondgSuite']) else: outputTable[i]['numFreqBpSecondgSuite'] = None if outputTable[i]['sumSecondgSuite'] != 0: outputTable[i]['numFreqUniqueBpSecondgSuite'] = float( outputTable[i]['numPairBpSecondgSuite']) / float( outputTable[i]['sumSecondgSuite']) else: outputTable[i]['numFreqUniqueBpSecondgSuite'] = None i += 1 # sortTable outputTableLine = [] for key, item in outputTable.iteritems(): line = [ item['id'], item['numSecondgSuite'], item['sumSecondgSuite'], item['numPairBpSecondgSuite'], item['numFreqBpSecondgSuite'], item['numFreqUniqueBpSecondgSuite'], item['numSecondgSuitePercentage'] ] outputTableLine.append(line) import operator outputTableLineSort = sorted(outputTableLine, key=operator.itemgetter(1), reverse=True) tableHeader = [ 'Region ID ', 'Number of cases with at least one event ', 'Total number of events', 'Genome coverage (unique bp)', 'Number of events per unique bp', 'Number of unique bp per event', 'Percentage of cases with at least one event' ] htmlCore = HtmlCore() htmlCore.begin() htmlCore.line( "<b>Identification of genomic elements with high event recurrence</b> " ) htmlCore.header(title) htmlCore.divBegin('resultsDiv') htmlCore.tableHeader(tableHeader, sortable=True, tableId='resultsTable') for line in outputTableLineSort: htmlCore.tableLine(line) plotRes = [] plotXAxis = [] for lineInx in range(1, len(outputTableLineSort[0])): plotResPart = [] plotXAxisPart = [] for lineInxO in range(0, len(outputTableLineSort)): # if outputTableLineSort[lineInxO][lineInx]!=0 and # if outputTableLineSort[lineInxO][lineInx]!=None: plotResPart.append(outputTableLineSort[lineInxO][lineInx]) plotXAxisPart.append(outputTableLineSort[lineInxO][0]) plotRes.append(plotResPart) plotXAxis.append(plotXAxisPart) htmlCore.tableFooter() htmlCore.divEnd() htmlCore.divBegin('plot', style='padding-top:20px;margin-top:20px;') vg = visualizationGraphs() res = vg.drawColumnCharts( plotRes, titleText=tableHeader[1:], categories=plotXAxis, height=500, xAxisRotation=270, xAxisTitle='Ragion ID', yAxisTitle='Number of cases with at least one event', marginTop=30, addTable=True, sortableAccordingToTable=True, legend=False) htmlCore.line(res) htmlCore.divEnd() htmlCore.hideToggle(styleClass='debug') htmlCore.end() print htmlCore
def execute(choices, galaxyFn=None, username=''): #targetTrackNames, targetTrackCollection, targetTrackGenome = getGSuiteDataFromGalaxyTN(choices.gSuiteFirst) gFirst = choices.gSuiteFirst.split(':') firstGSuite = ScreenTwoTrackCollectionsAgainstEachOther2LevelDepth.returnGSuiteDict3LevelDept( gFirst) gSecond = choices.gSuiteSecond.split(':') secondGSuite = ScreenTwoTrackCollectionsAgainstEachOther2LevelDepth.returnGSuiteDict2LevelDept( gSecond) regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) if choices.intraOverlap == ScreenTwoTrackCollectionsAgainstEachOther2LevelDepth.MERGE_INTRA_OVERLAPS: analysisDef = 'dummy -> RawOverlapStat' else: analysisDef = 'dummy [withOverlaps=yes] -> RawOverlapAllowSingleTrackOverlapsStat' if choices.type == 'basic': results = [] for elFG in firstGSuite: for elSG in secondGSuite: if elFG['genome'] == elSG['genome']: targetTrackGenome = elFG['genome'] resultPartList3 = [] for targetTrackDetailFolder1 in elFG[ 'dataFolderValue0']: resultPartList2 = [] for targetTrackDetail in targetTrackDetailFolder1[ 'dataFolderValue1']: resultPartList1 = [] for el in elSG['dataFolderValue0']: result = GalaxyInterface.runManual( [ targetTrackDetail['trackPath'], el['trackPath'] ], analysisDef, regSpec, binSpec, elFG['genome'].split('-')[0], galaxyFn, printRunDescription=False, printResults=False) resultPartList1.append({ 'refTrackName': el['trackName'].replace( targetTrackGenome, ''), 'data': processResult(result.getGlobalResult()) }) resultPartList2.append({ 'folderName2': targetTrackDetail['folderName2'], 'targetTrackName': targetTrackDetail['trackName'], 'dataFolderValue2': resultPartList1 }) resultPartList3.append({ 'folderName1': targetTrackDetailFolder1['folderName1'], 'dataFolderValue1': resultPartList2 }) results.append({ 'genome': targetTrackGenome, 'dataFolderValue0': resultPartList3 }) else: from quick.statistic.NumT2SegsTouchedByT1SegsStat import NumT2SegsTouchedByT1SegsStat results = [] for elFG in firstGSuite: for elSG in secondGSuite: if elFG['genome'] == elSG['genome']: if choices.statistic == 'Number of touched segments': analysisSpec = AnalysisSpec( NumT2SegsTouchedByT1SegsStat) #analysisBins = UserBinSource('*', '10m', genome=elFG['genome'].split('-')[0]) analysisBins = GlobalBinSource( elFG['genome'].split('-')[0]) targetTrackGenome = elFG['genome'] resultPartList3 = [] for targetTrackDetailFolder1 in elFG[ 'dataFolderValue0']: resultPartList2 = [] for targetTrackDetail in targetTrackDetailFolder1[ 'dataFolderValue1']: resultPartList1 = [] for el in elSG['dataFolderValue0']: res = doAnalysis( analysisSpec, analysisBins, [ PlainTrack( targetTrackDetail['trackPath'] ), PlainTrack(el['trackPath']) ]) resultDict = res.getGlobalResult() resultPartList1.append({ 'refTrackName': el['trackName'].replace( targetTrackGenome, ''), 'data': [resultDict['Result']] }) resultPartList2.append({ 'folderName2': targetTrackDetail['folderName2'], 'targetTrackName': targetTrackDetail['trackName'], 'dataFolderValue2': resultPartList1 }) resultPartList3.append({ 'folderName1': targetTrackDetailFolder1['folderName1'], 'dataFolderValue1': resultPartList2 }) results.append({ 'genome': targetTrackGenome, 'dataFolderValue0': resultPartList3 }) if choices.type == 'basic': stat = choices.statistic #statIndex = STAT_LIST_INDEX[stat] statIndex = ScreenTwoTrackCollectionsAgainstEachOther2LevelDepth.STAT_LIST_INDEX statIndex = statIndex.index(stat) else: stat = '0' statIndex = 0 htmlCore = HtmlCore() htmlCore.begin() htmlCore.line(""" <style type="text/css"> .hidden { display: none; { .visible { display: block; } </style> """) folderValue0Unique = [] folderValue1Unique = [] folderValue2Unique = [] targetTrackFeatureTitles = [] for dataDetail0 in results: if dataDetail0['genome'] not in folderValue0Unique: folderValue0Unique.append(dataDetail0['genome']) for dataDetail1 in dataDetail0['dataFolderValue0']: if dataDetail1['folderName1'] not in folderValue1Unique: folderValue1Unique.append(dataDetail1['folderName1']) for dataDetail2 in dataDetail1['dataFolderValue1']: if dataDetail2['folderName2'] not in folderValue2Unique: folderValue2Unique.append(dataDetail2['folderName2']) for dataDetail3 in dataDetail2['dataFolderValue2']: if dataDetail3[ 'refTrackName'] not in targetTrackFeatureTitles: targetTrackFeatureTitles.append( dataDetail3['refTrackName']) #print 'folderValue0Unique=' + str(folderValue0Unique) #print 'folderValue1Unique=' + str(folderValue1Unique) #print 'folderValue2Unique=' + str(folderValue2Unique) #print 'targetTrackFeatureTitles=' + str(targetTrackFeatureTitles) targetTrackNameList = targetTrackFeatureTitles htmlCore.line('Statistic: ' + stat) htmlCore.line( addJS3levelOptionList(folderValue1Unique, folderValue2Unique, targetTrackFeatureTitles, targetTrackNameList, folderValue0Unique)) htmlCore.divBegin('results') #htmlCore.paragraph(preporcessResults(results, folderValue1Unique, folderValue2Unique, targetTrackFeatureTitles, statIndex)) htmlCore.paragraph( preporcessResults3(results, folderValue1Unique, folderValue2Unique, targetTrackFeatureTitles, folderValue0Unique, statIndex)) htmlCore.divEnd() htmlCore.hideToggle(styleClass='debug') htmlCore.end() print htmlCore
def countStatistics(similarityFunc, choices, genome, tracks, trackTitles): trackList = tracks[1:] resultsForStatistics = OrderedDict() llDict = OrderedDict() trackT = trackTitles[1:] i = 0 for tt1 in trackT: if not tt1 in llDict: llDict[tt1] = [] resultsForStatistics[tt1] = {} for tt2 in range(i, len(trackT)): llDict[tt1].append(trackT[tt2]) i += 1 # # print 'llDict=' + str(llDict) # print 'trackT=' + str(trackT) # print 'trackList=' + str(trackList) for key0, it0 in llDict.iteritems(): if len(it0) > 1: trackCollection = [] for it1 in it0: trackNumber = trackT.index(it1) trackCollection.append(trackList[trackNumber]) trackTitles = CommonConstants.TRACK_TITLES_SEPARATOR.join(it0) # print str(key0) + '- trackCollection: ' + str(trackCollection) + ' trackTitles: ' + str(trackTitles) for similarityStatClassName in similarityFunc: regSpec, binSpec = UserBinMixin.getRegsAndBinsSpec(choices) analysisBins = GalaxyInterface._getUserBinSource( regSpec, binSpec, genome=genome) mcfdrDepth = AnalysisDefHandler( REPLACE_TEMPLATES['$MCFDR$']).getOptionsAsText( ).values()[0][0] analysisDefString = REPLACE_TEMPLATES[ '$MCFDR$'] + ' -> GSuiteSimilarityToQueryTrackRankingsAndPValuesWrapperStat' analysisSpec = AnalysisDefHandler(analysisDefString) analysisSpec.setChoice('MCFDR sampling depth', mcfdrDepth) analysisSpec.addParameter( 'assumptions', 'PermutedSegsAndIntersegsTrack_') analysisSpec.addParameter( 'rawStatistic', GSuiteStatUtils.PAIRWISE_STAT_LABEL_TO_CLASS_MAPPING[ similarityStatClassName]) analysisSpec.addParameter( 'pairwiseStatistic', GSuiteStatUtils.PAIRWISE_STAT_LABEL_TO_CLASS_MAPPING[ similarityStatClassName] ) #needed for call of non randomized stat for assertion analysisSpec.addParameter('tail', 'more') analysisSpec.addParameter( 'trackTitles', trackTitles) #that need to be string #i added that one later analysisSpec.addParameter('queryTracksNum', str(len(trackCollection))) results = doAnalysis(analysisSpec, analysisBins, trackCollection).getGlobalResult() if not similarityStatClassName in resultsForStatistics[ key0]: resultsForStatistics[key0][ similarityStatClassName] = {} resultsForStatistics[key0][ similarityStatClassName] = results return resultsForStatistics
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() heatmapPresenter = HeatmapFromTableDataPresenter(resultsObj, baseDir=baseDir, header='Overlapping base-pairs between the tracks of the two suites', printDimensions=False) tablePresenter = MatrixGlobalValueFromTableDataPresenter(resultsObj, baseDir=baseDir, header='Table of overlapping base-pairs 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(tablePresenter.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(heatmapPresenter.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(tablePresenter.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(heatmapPresenter.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)
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) analysisSpec.addParameter('queryTracksNum', len(tracks)) 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(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
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
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