Esempio n. 1
0
    def run(self):
        img = IMG()

        fout = open('./data/evaluate_prodigal.txt', 'w', 1)

        # get list of all marker genes
        markerset = MarkerSet()
        pfamMarkers, tigrMarkers = markerset.getCalculatedMarkerGenes()

        print 'PFAM marker genes: ' + str(len(tigrMarkers))
        print 'TIGR marker genes: ' + str(len(pfamMarkers))
        print ''

        # run HMMs on each of the finished genomes
        genomeIds = img.genomeIds('Finished')
        for genomeId in genomeIds:
            print genomeId + ':'
            fout.write(genomeId + ':\n')

            self.runProdigal(genomeId)
            self.runGeneMark(genomeId)

            self.runPFAM(genomeId)
            self.runTIGRFAM(genomeId)

            self.compareResults(genomeId, pfamMarkers, tigrMarkers, fout)

        fout.close()
Esempio n. 2
0
    def run(self):
        img = IMG()

        fout = open('./data/evaluate_prodigal.txt', 'w', 1)

        # get list of all marker genes
        markerset = MarkerSet()
        pfamMarkers, tigrMarkers = markerset.getCalculatedMarkerGenes()

        print('PFAM marker genes: ' + str(len(tigrMarkers)))
        print('TIGR marker genes: ' + str(len(pfamMarkers)))
        print('')

        # run HMMs on each of the finished genomes
        genomeIds = img.genomeIds('Finished')
        for genomeId in genomeIds:
            print(genomeId + ':')
            fout.write(genomeId + ':\n')

            self.runProdigal(genomeId)
            self.runGeneMark(genomeId)

            self.runPFAM(genomeId)
            self.runTIGRFAM(genomeId)

            self.compareResults(genomeId, pfamMarkers, tigrMarkers, fout)

        fout.close()
Esempio n. 3
0
    def run(self, minGenomes, minMarkerSets):
        img = IMG()
        pfam = PFAM()

        # get list of all marker genes
        markerset = MarkerSet()
        pfamIds, tigrIds = markerset.getCalculatedMarkerGenes()

        print 'TIGR marker genes: ' + str(len(tigrIds))
        print 'PFAM marker genes: ' + str(len(pfamIds))

        # get all PFAM HMMs that are in the same clan
        # as any of the marker genes
        pfamIdToClanId = pfam.pfamIdToClanId()
        clans = set()
        for pfamId in pfamIds:
            if pfamId.replace('PF', 'pfam') in pfamIdToClanId:
                clans.add(pfamIdToClanId[pfamId])

        for pfamId, clanId in pfamIdToClanId.iteritems():
            if clanId in clans:
                pfamIds.add(pfamId)

        print '  PFAM HMMs require to cover marker gene clans: ' + str(
            len(pfamIds))

        # get name of each PFAM HMM
        fout = open('./hmm/pfam.keyfile.txt', 'w')
        pfamNames = []
        for line in open(img.pfamHMMs):
            if 'NAME' in line:
                name = line[line.find(' '):].strip()
            elif 'ACC' in line:
                acc = line[line.find(' '):line.rfind('.')].strip()
                if acc.replace('PF', 'pfam') in pfamIds:
                    pfamNames.append(name)
                    fout.write(name + '\n')
        fout.close()

        print 'PFAM names: ' + str(len(pfamNames))

        # extract each PFAM HMM
        os.system('hmmfetch -f ' + img.pfamHMMs +
                  ' ./hmm/pfam.keyfile.txt > ./hmm/pfam_markers.hmm')

        # get name of each PFAM HMM
        fout = open('./hmm/tigr.keyfile.txt', 'w')
        for tigrId in tigrIds:
            fout.write(tigrId + '\n')
        fout.close()

        # extract each PFAM HMM
        os.system('hmmfetch -f ' + img.tigrHMMs +
                  ' ./hmm/tigr.keyfile.txt > ./hmm/tigr_markers.hmm')
    def run(self, ubiquityThreshold, singleCopyThreshold, minGenomes, mostSpecificRank, minMarkers, completenessThreshold, contaminationThreshold):
        print 'Ubiquity threshold: ' + str(ubiquityThreshold)
        print 'Single-copy threshold: ' + str(singleCopyThreshold)
        print 'Min. genomes: ' + str(minGenomes)
        print 'Most specific taxonomic rank: ' + str(mostSpecificRank)
        print 'Min markers: ' + str(minMarkers)
        print 'Completeness threshold: ' + str(completenessThreshold)
        print 'Contamination threshold: ' + str(contaminationThreshold)

        img = IMG()
        markerset = MarkerSet()

        lineages = img.lineagesByCriteria(minGenomes, mostSpecificRank)

        degenerateGenomes = {}
        for lineage in lineages:
            genomeIds = img.genomeIdsByTaxonomy(lineage, 'Final')

            print ''
            print 'Lineage ' + lineage + ' contains ' + str(len(genomeIds)) + ' genomes.'

            # get table of PFAMs and do some initial filtering to remove PFAMs that are
            # clearly not going to pass the ubiquity and single-copy thresholds
            countTable = img.countTable(genomeIds)
            countTable = img.filterTable(genomeIds, countTable, ubiquityThreshold*0.9, singleCopyThreshold*0.9)

            markerGenes = markerset.markerGenes(genomeIds, countTable, ubiquityThreshold*len(genomeIds), singleCopyThreshold*len(genomeIds))
            if len(markerGenes) < minMarkers:
                continue

            geneDistTable = img.geneDistTable(genomeIds, markerGenes, spacingBetweenContigs=1e6)
            colocatedGenes = markerset.colocatedGenes(geneDistTable)
            colocatedSets = markerset.colocatedSets(colocatedGenes, markerGenes)

            for genomeId in genomeIds:
                completeness, contamination = markerset.genomeCheck(colocatedSets, genomeId, countTable)

                if completeness < completenessThreshold or contamination > contaminationThreshold:
                    degenerateGenomes[genomeId] = degenerateGenomes.get(genomeId, []) + [[lineage.split(';')[-1].strip(), len(genomeIds), len(colocatedSets), completeness, contamination]]

        # write out degenerate genomes
        metadata = img.genomeMetadata('Final')

        fout = open('./data/degenerate_genomes.tsv', 'w')
        fout.write('Genome Id\tTaxonomy\tGenome Size (Gbps)\tScaffolds\tBiotic Relationships\tStatus\tLineage\t# genomes\tMarker set size\tCompleteness\tContamination\n')
        for genomeId, data in degenerateGenomes.iteritems():
            fout.write(genomeId + '\t' + '; '.join(metadata[genomeId]['taxonomy']) + '\t%.2f' % (float(metadata[genomeId]['genome size']) / 1e6) + '\t' + str(metadata[genomeId]['scaffold count']))
            fout.write('\t' + metadata[genomeId]['biotic relationships'] + '\t' + metadata[genomeId]['status'])

            for d in data:
                fout.write('\t' + d[0] + '\t' + str(d[1]) + '\t' + str(d[2]) + '\t%.3f\t%.3f' % (d[3], d[4]))
            fout.write('\n')

        fout.close()
Esempio n. 5
0
    def run(self, ubiquityThreshold, singleCopyThreshold, rank):
        img = IMG()
        markerset = MarkerSet()

        print('Reading metadata.')
        metadata = img.genomeMetadata()
        print('  Genomes with metadata: ' + str(len(metadata)))

        # calculate marker set for each lineage at the specified rank
        sortedLineages = img.lineagesSorted(metadata, rank)
        markerGeneLists = {}
        for lineage in sortedLineages:
            taxonomy = lineage.split(';')
            if len(taxonomy) != rank + 1:
                continue

        genomeIds = img.genomeIdsByTaxonomy(lineage, metadata, 'Final')
        countTable = img.countTable(genomeIds)

        if len(genomeIds) < 3:
            continue

        print('Lineage ' + lineage + ' contains ' + str(len(genomeIds)) +
              ' genomes.')

        markerGenes = markerset.markerGenes(
            genomeIds, countTable, ubiquityThreshold * len(genomeIds),
            singleCopyThreshold * len(genomeIds))

        print('  Marker genes: ' + str(len(markerGenes)))
        print('')

        markerGeneLists[lineage] = markerGenes

        # calculate union of marker gene list for higher taxonomic groups
        for r in range(rank - 1, -1, -1):
            print('Processing rank ' + str(r))
            rankMarkerGeneLists = {}
            for lineage, markerGenes in markerGeneLists.iteritems():
                taxonomy = lineage.split(';')
                if len(taxonomy) != r + 2:
                    continue

                curLineage = '; '.join(taxonomy[0:r + 1])
                if curLineage not in rankMarkerGeneLists:
                    rankMarkerGeneLists[curLineage] = markerGenes
                else:
                    curMarkerGenes = rankMarkerGeneLists[curLineage]
                    curMarkerGenes = curMarkerGenes.intersection(markerGenes)
                    rankMarkerGeneLists[curLineage] = curMarkerGenes

            # combine marker gene list dictionaries
            markerGeneLists.update(rankMarkerGeneLists)
Esempio n. 6
0
    def run(
        self,
        ubiquityThreshold,
        singleCopyThreshold,
        minGenomes,
        minMarkers,
        mostSpecificRank,
        distThreshold,
        genomeThreshold,
    ):
        img = IMG()
        markerset = MarkerSet()

        lineages = img.lineagesSorted(mostSpecificRank)

        fout = open("./data/colocated.tsv", "w", 1)
        fout.write("Lineage\t# genomes\t# markers\t# co-located sets\tCo-located markers\n")

        lineageCount = 0
        for lineage in lineages:
            lineageCount += 1

            genomeIds = img.genomeIdsByTaxonomy(lineage, "Final")
            if len(genomeIds) < minGenomes:
                continue

            countTable = img.countTable(genomeIds)
            markerGenes = markerset.markerGenes(
                genomeIds, countTable, ubiquityThreshold * len(genomeIds), singleCopyThreshold * len(genomeIds)
            )

            geneDistTable = img.geneDistTable(genomeIds, markerGenes)
            colocatedGenes = markerset.colocatedGenes(geneDistTable, distThreshold, genomeThreshold)
            colocatedSets = markerset.colocatedSets(colocatedGenes, markerGenes)
            if len(colocatedSets) < minMarkers:
                continue

            print "\nLineage " + lineage + " contains " + str(len(genomeIds)) + " genomes (" + str(
                lineageCount
            ) + " of " + str(len(lineages)) + ")."
            print "  Marker genes: " + str(len(markerGenes))
            print "  Co-located gene sets: " + str(len(colocatedSets))

            fout.write(
                lineage + "\t" + str(len(genomeIds)) + "\t" + str(len(markerGenes)) + "\t" + str(len(colocatedSets))
            )
            for cs in colocatedSets:
                fout.write("\t" + ", ".join(cs))
            fout.write("\n")

        fout.close()
Esempio n. 7
0
    def run(self, minGenomes, minMarkerSets):
        img = IMG()
        pfam = PFAM()

        # get list of all marker genes
        markerset = MarkerSet()
        pfamIds, tigrIds = markerset.getCalculatedMarkerGenes()

        print 'TIGR marker genes: ' + str(len(tigrIds))
        print 'PFAM marker genes: ' + str(len(pfamIds))

        # get all PFAM HMMs that are in the same clan
        # as any of the marker genes
        pfamIdToClanId = pfam.pfamIdToClanId()
        clans = set()
        for pfamId in pfamIds:
            if pfamId.replace('PF', 'pfam') in pfamIdToClanId:
                clans.add(pfamIdToClanId[pfamId])

        for pfamId, clanId in pfamIdToClanId.iteritems():
            if clanId in clans:
                pfamIds.add(pfamId)

        print '  PFAM HMMs require to cover marker gene clans: ' + str(len(pfamIds))

        # get name of each PFAM HMM
        fout = open('./hmm/pfam.keyfile.txt', 'w')
        pfamNames = []
        for line in open(img.pfamHMMs):
            if 'NAME' in line:
                name = line[line.find(' '):].strip()
            elif 'ACC' in line:
                acc = line[line.find(' '):line.rfind('.')].strip()
                if acc.replace('PF', 'pfam') in pfamIds:
                    pfamNames.append(name)
                    fout.write(name + '\n')
        fout.close()

        print 'PFAM names: ' + str(len(pfamNames))

        # extract each PFAM HMM
        os.system('hmmfetch -f ' + img.pfamHMMs + ' ./hmm/pfam.keyfile.txt > ./hmm/pfam_markers.hmm')

        # get name of each PFAM HMM
        fout = open('./hmm/tigr.keyfile.txt', 'w')
        for tigrId in tigrIds:
            fout.write(tigrId + '\n')
        fout.close()

        # extract each PFAM HMM
        os.system('hmmfetch -f ' + img.tigrHMMs + ' ./hmm/tigr.keyfile.txt > ./hmm/tigr_markers.hmm')
    def run(self, ubiquityThreshold, singleCopyThreshold, rank):
        img = IMG()
        markerset = MarkerSet()

        print 'Reading metadata.'
        metadata = img.genomeMetadata()
        print '  Genomes with metadata: ' + str(len(metadata))

        # calculate marker set for each lineage at the specified rank
        sortedLineages = img.lineagesSorted(metadata, rank)
        markerGeneLists = {}
        for lineage in sortedLineages:
            taxonomy = lineage.split(';')
            if len(taxonomy) != rank+1:
                continue

        genomeIds = img.genomeIdsByTaxonomy(lineage, metadata, 'Final')
        countTable = img.countTable(genomeIds)

        if len(genomeIds) < 3:
            continue

        print 'Lineage ' + lineage + ' contains ' + str(len(genomeIds)) + ' genomes.'

        markerGenes = markerset.markerGenes(genomeIds, countTable, ubiquityThreshold*len(genomeIds), singleCopyThreshold*len(genomeIds))

        print '  Marker genes: ' + str(len(markerGenes))
        print ''

        markerGeneLists[lineage] = markerGenes

        # calculate union of marker gene list for higher taxonomic groups
        for r in xrange(rank-1, -1, -1):
            print 'Processing rank ' + str(r)
            rankMarkerGeneLists = {}
            for lineage, markerGenes in markerGeneLists.iteritems():
                taxonomy = lineage.split(';')
                if len(taxonomy) != r+2:
                    continue

                curLineage = '; '.join(taxonomy[0:r+1])
                if curLineage not in rankMarkerGeneLists:
                    rankMarkerGeneLists[curLineage] = markerGenes
                else:
                    curMarkerGenes = rankMarkerGeneLists[curLineage]
                    curMarkerGenes = curMarkerGenes.intersection(markerGenes)
                    rankMarkerGeneLists[curLineage] = curMarkerGenes

            # combine marker gene list dictionaries
            markerGeneLists.update(rankMarkerGeneLists)
Esempio n. 9
0
    def run(self, ubiquityThreshold, singleCopyThreshold, minGenomes,
            minMarkers, mostSpecificRank, distThreshold, genomeThreshold):
        img = IMG()
        markerset = MarkerSet()

        lineages = img.lineagesSorted(mostSpecificRank)

        fout = open('./data/colocated.tsv', 'w', 1)
        fout.write(
            'Lineage\t# genomes\t# markers\t# co-located sets\tCo-located markers\n'
        )

        lineageCount = 0
        for lineage in lineages:
            lineageCount += 1

            genomeIds = img.genomeIdsByTaxonomy(lineage, 'Final')
            if len(genomeIds) < minGenomes:
                continue

            countTable = img.countTable(genomeIds)
            markerGenes = markerset.markerGenes(
                genomeIds, countTable, ubiquityThreshold * len(genomeIds),
                singleCopyThreshold * len(genomeIds))

            geneDistTable = img.geneDistTable(genomeIds,
                                              markerGenes,
                                              spacingBetweenContigs=1e6)
            colocatedGenes = markerset.colocatedGenes(geneDistTable,
                                                      distThreshold,
                                                      genomeThreshold)
            colocatedSets = markerset.colocatedSets(colocatedGenes,
                                                    markerGenes)
            if len(colocatedSets) < minMarkers:
                continue

            print '\nLineage ' + lineage + ' contains ' + str(len(
                genomeIds)) + ' genomes (' + str(lineageCount) + ' of ' + str(
                    len(lineages)) + ').'
            print '  Marker genes: ' + str(len(markerGenes))
            print '  Co-located gene sets: ' + str(len(colocatedSets))

            fout.write(lineage + '\t' + str(len(genomeIds)) + '\t' +
                       str(len(markerGenes)) + '\t' + str(len(colocatedSets)))
            for cs in colocatedSets:
                fout.write('\t' + ', '.join(cs))
            fout.write('\n')

        fout.close()
Esempio n. 10
0
    def run(self, ubiquityThreshold, singleCopyThreshold, minGenomes, minMarkers, mostSpecificRank, distThreshold, genomeThreshold):
        img = IMG()
        markerset = MarkerSet()

        lineages = img.lineagesSorted(mostSpecificRank)

        fout = open('./data/colocated.tsv', 'w', 1)
        fout.write('Lineage\t# genomes\t# markers\t# co-located sets\tCo-located markers\n')

        lineageCount = 0
        for lineage in lineages:
            lineageCount += 1

            genomeIds = img.genomeIdsByTaxonomy(lineage, 'Final')
            if len(genomeIds) < minGenomes:
                continue

            countTable = img.countTable(genomeIds)
            markerGenes = markerset.markerGenes(genomeIds, countTable, ubiquityThreshold*len(genomeIds), singleCopyThreshold*len(genomeIds))

            geneDistTable = img.geneDistTable(genomeIds, markerGenes, spacingBetweenContigs=1e6)
            colocatedGenes = markerset.colocatedGenes(geneDistTable, distThreshold, genomeThreshold)
            colocatedSets = markerset.colocatedSets(colocatedGenes, markerGenes)
            if len(colocatedSets) < minMarkers:
                continue

            print '\nLineage ' + lineage + ' contains ' + str(len(genomeIds)) + ' genomes (' + str(lineageCount) + ' of ' + str(len(lineages)) + ').'
            print '  Marker genes: ' + str(len(markerGenes))
            print '  Co-located gene sets: ' + str(len(colocatedSets))

            fout.write(lineage + '\t' + str(len(genomeIds)) + '\t' + str(len(markerGenes)) + '\t' + str(len(colocatedSets)))
            for cs in colocatedSets:
                fout.write('\t' + ', '.join(cs))
            fout.write('\n')

        fout.close()
    def run(self, taxonomyStr, ubiquityThreshold, singleCopyThreshold, numBins, numRndGenomes):
        img = IMG()
        markerSet = MarkerSet()

        metadata = img.genomeMetadata()
        lineageGenomeIds = img.genomeIdsByTaxonomy(taxonomyStr, metadata)

        # build marker set from finished prokaryotic genomes
        genomeIds = []
        for genomeId in lineageGenomeIds:
            if metadata[genomeId]['status'] == 'Finished' and (metadata[genomeId]['taxonomy'][0] == 'Bacteria' or metadata[genomeId]['taxonomy'][0] == 'Archaea'):
                genomeIds.append(genomeId)
        genomeIds = set(genomeIds) - img.genomesWithMissingData(genomeIds)

        print 'Lineage ' + taxonomyStr + ' contains ' + str(len(genomeIds)) + ' genomes.'

        # get marker set
        countTable = img.countTable(genomeIds)
        countTable = img.filterTable(genomeIds, countTable, 0.9*ubiquityThreshold, 0.9*singleCopyThreshold)
        markerGenes = markerSet.markerGenes(genomeIds, countTable, ubiquityThreshold*len(genomeIds), singleCopyThreshold*len(genomeIds))
        tigrToRemove = img.identifyRedundantTIGRFAMs(markerGenes)
        markerGenes = markerGenes - tigrToRemove
        geneDistTable = img.geneDistTable(genomeIds, markerGenes, spacingBetweenContigs=1e6)

        print 'Number of marker genes: ' + str(len(markerGenes))

        # randomly set genomes to plot
        if numRndGenomes != -1:
            genomeIds = random.sample(list(genomeIds), numRndGenomes)
        genomeIds = set(genomeIds)

        # plot distribution of marker genes
        filename = 'geneDistribution.' + taxonomyStr.replace(';','_') + '.' + str(ubiquityThreshold) + '-' + str(singleCopyThreshold) + '.tsv'
        fout = open(filename, 'w')
        fout.write('Genome ID\tLineage\tNumber of Genes\tUniformity\tDistribution\n')
        matrix = []
        rowLabels = []
        for genomeId in genomeIds:
            binSize = float(metadata[genomeId]['genome size']) / numBins

            binCounts = [0]*numBins
            pts = []
            for _, data in geneDistTable[genomeId].iteritems():
                for genePos in data:
                    binNum = int(genePos[1] / binSize)
                    binCounts[binNum] += 1
                    pts.append(genePos[1])
            matrix.append(binCounts)

            u = markerSet.uniformity(metadata[genomeId]['genome size'], pts)

            fout.write(genomeId + '\t' + '; '.join(metadata[genomeId]['taxonomy']) + '\t' + str(len(geneDistTable[genomeId])) + '\t%.3f' % u)
            for b in xrange(0, numBins):
                fout.write('\t' + str(binCounts[b]))
            fout.write('\n')

            rowLabels.append('%.2f' % u + ', ' + str(genomeId) + ' - ' + '; '.join(metadata[genomeId]['taxonomy'][0:5]))

        fout.close()

        # plot data
        heatmap = Heatmap()
        plotFilename = 'geneDistribution.' + taxonomyStr.replace(';','_') + '.' + str(ubiquityThreshold) + '-' + str(singleCopyThreshold) + '.png'
        heatmap.plot(plotFilename, matrix, rowLabels, 0.6)
Esempio n. 12
0
 def __init__(self):
     self.img = IMG()
     self.markerset = MarkerSet()
Esempio n. 13
0
    def run(self, ubiquityThreshold, singleCopyThreshold, trustedCompleteness,
            trustedContamination, genomeCompleteness, genomeContamination):
        img = IMG()
        markerset = MarkerSet()

        metadata = img.genomeMetadata()

        trustedOut = open('./data/trusted_genomes.tsv', 'w')
        trustedOut.write(
            'Genome Id\tLineage\tGenome size (Mbps)\tScaffold count\tBiotic Relationship\tStatus\tCompleteness\tContamination\n'
        )

        filteredOut = open('./data/filtered_genomes.tsv', 'w')
        filteredOut.write(
            'Genome Id\tLineage\tGenome size (Mbps)\tScaffold count\tBiotic Relationship\tStatus\tCompleteness\tContamination\n'
        )

        allGenomeIds = set()
        allTrustedGenomeIds = set()
        for lineage in ['Archaea', 'Bacteria']:
            # get all genomes in lineage and build gene count table
            print '\nBuilding gene count table.'
            allLineageGenomeIds = img.genomeIdsByTaxonomy(
                lineage, metadata, 'All')
            countTable = img.countTable(allLineageGenomeIds)
            countTable = img.filterTable(allLineageGenomeIds, countTable,
                                         0.9 * ubiquityThreshold,
                                         0.9 * singleCopyThreshold)

            # get all genomes from specific lineage
            allGenomeIds = allGenomeIds.union(allLineageGenomeIds)

            print 'Lineage ' + lineage + ' contains ' + str(
                len(allLineageGenomeIds)) + ' genomes.'

            # tabulate genomes from each phylum
            allPhylumCounts = {}
            for genomeId in allLineageGenomeIds:
                taxon = metadata[genomeId]['taxonomy'][1]
                allPhylumCounts[taxon] = allPhylumCounts.get(taxon, 0) + 1

            # identify marker set for genomes
            markerGenes = markerset.markerGenes(
                allLineageGenomeIds, countTable,
                ubiquityThreshold * len(allLineageGenomeIds),
                singleCopyThreshold * len(allLineageGenomeIds))
            print '  Marker genes: ' + str(len(markerGenes))

            geneDistTable = img.geneDistTable(allLineageGenomeIds,
                                              markerGenes,
                                              spacingBetweenContigs=1e6)
            colocatedGenes = markerset.colocatedGenes(geneDistTable, metadata)
            colocatedSets = markerset.colocatedSets(colocatedGenes,
                                                    markerGenes)
            print '  Marker set size: ' + str(len(colocatedSets))

            # identifying trusted genomes (highly complete, low contamination genomes)
            trustedGenomeIds = set()
            for genomeId in allLineageGenomeIds:
                completeness, contamination = markerset.genomeCheck(
                    colocatedSets, genomeId, countTable)

                if completeness >= trustedCompleteness and contamination <= trustedContamination:
                    trustedGenomeIds.add(genomeId)
                    allTrustedGenomeIds.add(genomeId)

                    trustedOut.write(genomeId + '\t' +
                                     '; '.join(metadata[genomeId]['taxonomy']))
                    trustedOut.write(
                        '\t%.2f' %
                        (float(metadata[genomeId]['genome size']) / 1e6))
                    trustedOut.write('\t' +
                                     str(metadata[genomeId]['scaffold count']))
                    trustedOut.write(
                        '\t' + metadata[genomeId]['biotic relationships'])
                    trustedOut.write('\t' + metadata[genomeId]['status'])
                    trustedOut.write('\t%.3f\t%.3f' %
                                     (completeness, contamination) + '\n')
                else:
                    filteredOut.write(
                        genomeId + '\t' +
                        '; '.join(metadata[genomeId]['taxonomy']))
                    filteredOut.write(
                        '\t%.2f' %
                        (float(metadata[genomeId]['genome size']) / 1e6))
                    filteredOut.write(
                        '\t' + str(metadata[genomeId]['scaffold count']))
                    filteredOut.write(
                        '\t' + metadata[genomeId]['biotic relationships'])
                    filteredOut.write('\t' + metadata[genomeId]['status'])
                    filteredOut.write('\t%.3f\t%.3f' %
                                      (completeness, contamination) + '\n')

            print '  Trusted genomes: ' + str(len(trustedGenomeIds))

            # determine status of trusted genomes
            statusBreakdown = {}
            for genomeId in trustedGenomeIds:
                statusBreakdown[metadata[genomeId]
                                ['status']] = statusBreakdown.get(
                                    metadata[genomeId]['status'], 0) + 1

            print '  Trusted genome status breakdown: '
            for status, count in statusBreakdown.iteritems():
                print '    ' + status + ': ' + str(count)

            # determine status of retained genomes
            proposalNameBreakdown = {}
            for genomeId in trustedGenomeIds:
                proposalNameBreakdown[metadata[genomeId][
                    'proposal name']] = proposalNameBreakdown.get(
                        metadata[genomeId]['proposal name'], 0) + 1

            print '  Retained genome proposal name breakdown: '
            for pn, count in proposalNameBreakdown.iteritems():
                if 'KMG' in pn or 'GEBA' in pn or 'HMP' in pn:
                    print '    ' + pn + ': ' + str(count)

            print '  Filtered genomes by phylum:'
            trustedPhylumCounts = {}
            for genomeId in trustedGenomeIds:
                taxon = metadata[genomeId]['taxonomy'][1]
                trustedPhylumCounts[taxon] = trustedPhylumCounts.get(taxon,
                                                                     0) + 1

            for phylum, count in allPhylumCounts.iteritems():
                print phylum + ': %d of %d' % (trustedPhylumCounts.get(
                    phylum, 0), count)

        trustedOut.close()
        filteredOut.close()

        # write out lineage statistics for genome distribution
        allStats = {}
        trustedStats = {}

        for r in xrange(0, 6):  # Domain to Genus
            for genomeId, data in metadata.iteritems():
                taxaStr = '; '.join(data['taxonomy'][0:r + 1])
                allStats[taxaStr] = allStats.get(taxaStr, 0) + 1
                if genomeId in allTrustedGenomeIds:
                    trustedStats[taxaStr] = trustedStats.get(taxaStr, 0) + 1

        sortedLineages = img.lineagesSorted()

        fout = open('./data/lineage_stats.tsv', 'w')
        fout.write('Lineage\tGenomes with metadata\tTrusted genomes\n')
        for lineage in sortedLineages:
            fout.write(lineage + '\t' + str(allStats.get(lineage, 0)) + '\t' +
                       str(trustedStats.get(lineage, 0)) + '\n')
        fout.close()
Esempio n. 14
0
class MarkerSetStability(object):
    def __init__(self):
        self.img = IMG()
        self.markerset = MarkerSet()

    def __processLineage(self, metadata, ubiquityThreshold,
                         singleCopyThreshold, minGenomes, queueIn, queueOut):
        """Assess stability of marker set for a specific named taxonomic group."""
        while True:
            lineage = queueIn.get(block=True, timeout=None)
            if lineage == None:
                break

            genomeIds = self.img.genomeIdsByTaxonomy(lineage, metadata,
                                                     'trusted')

            changeMarkerSetSize = {}
            markerGenes = []
            if len(genomeIds) >= minGenomes:
                # calculate marker set for all genomes in lineage
                geneCountTable = self.img.geneCountTable(genomeIds)
                markerGenes = self.markerset.markerGenes(
                    genomeIds, geneCountTable,
                    ubiquityThreshold * len(genomeIds),
                    singleCopyThreshold * len(genomeIds))
                tigrToRemove = self.img.identifyRedundantTIGRFAMs(markerGenes)
                markerGenes = markerGenes - tigrToRemove

                for selectPer in range(50, 101, 5):
                    numGenomesToSelect = int(
                        float(selectPer) / 100 * len(genomeIds))
                    perChange = []
                    for _ in range(0, 10):
                        # calculate marker set for subset of genomes
                        subsetGenomeIds = random.sample(
                            genomeIds, numGenomesToSelect)
                        geneCountTable = self.img.geneCountTable(
                            subsetGenomeIds)
                        subsetMarkerGenes = self.markerset.markerGenes(
                            subsetGenomeIds, geneCountTable,
                            ubiquityThreshold * numGenomesToSelect,
                            singleCopyThreshold * numGenomesToSelect)
                        tigrToRemove = self.img.identifyRedundantTIGRFAMs(
                            subsetMarkerGenes)
                        subsetMarkerGenes = subsetMarkerGenes - tigrToRemove

                        perChange.append(
                            float(
                                len(
                                    markerGenes.symmetric_difference(
                                        subsetMarkerGenes))) * 100.0 /
                            len(markerGenes))

                    changeMarkerSetSize[selectPer] = [
                        mean(perChange), std(perChange)
                    ]

            queueOut.put((lineage, len(genomeIds), len(markerGenes),
                          changeMarkerSetSize))

    def __storeResults(self, outputFile, totalLineages, writerQueue):
        """Store results to file."""

        fout = open(outputFile, 'w')
        fout.write(
            'Lineage\t# genomes\t# markers\tsubsample %\tmean % change\tstd % change\n'
        )

        numProcessedLineages = 0
        while True:
            lineage, numGenomes, numMarkerGenes, changeMarkerSetSize = writerQueue.get(
                block=True, timeout=None)
            if lineage == None:
                break

            numProcessedLineages += 1
            statusStr = '    Finished processing %d of %d (%.2f%%) lineages.' % (
                numProcessedLineages, totalLineages,
                float(numProcessedLineages) * 100 / totalLineages)
            sys.stdout.write('%s\r' % statusStr)
            sys.stdout.flush()

            for selectPer in sorted(changeMarkerSetSize.keys()):
                fout.write('%s\t%d\t%d\t%d\t%f\t%f\n' %
                           (lineage, numGenomes, numMarkerGenes, selectPer,
                            changeMarkerSetSize[selectPer][0],
                            changeMarkerSetSize[selectPer][1]))

        sys.stdout.write('\n')

        fout.close()

    def run(self, outputFile, ubiquityThreshold, singleCopyThreshold,
            minGenomes, mostSpecificRank, numThreads):
        """Calculate stability of marker sets for named taxonomic groups."""

        print('  Calculating stability of marker sets:')

        random.seed(1)

        # process each sequence in parallel
        workerQueue = mp.Queue()
        writerQueue = mp.Queue()

        metadata = self.img.genomeMetadata()
        lineages = self.img.lineagesByCriteria(metadata, minGenomes,
                                               mostSpecificRank)

        #lineages = ['Bacteria']
        #lineages += ['Bacteria;Proteobacteria']
        #lineages += ['Bacteria;Proteobacteria;Gammaproteobacteria']
        #lineages += ['Bacteria;Proteobacteria;Gammaproteobacteria;Enterobacteriales']
        #lineages += ['Bacteria;Proteobacteria;Gammaproteobacteria;Enterobacteriales;Enterobacteriaceae']
        #lineages += ['Bacteria;Proteobacteria;Gammaproteobacteria;Enterobacteriales;Enterobacteriaceae;Escherichia']
        #lineages += ['Bacteria;Proteobacteria;Gammaproteobacteria;Enterobacteriales;Enterobacteriaceae;Escherichia;coli']

        #lineages = ['Archaea']
        #lineages += ['Archaea;Euryarchaeota']
        #lineages += ['Archaea;Euryarchaeota;Methanomicrobia']
        #lineages += ['Archaea;Euryarchaeota;Methanomicrobia;Methanosarcinales']
        #lineages += ['Archaea;Euryarchaeota;Methanomicrobia;Methanosarcinales;Methanosarcinaceae']

        for lineage in lineages:
            workerQueue.put(lineage)

        for _ in range(numThreads):
            workerQueue.put(None)

        calcProc = [
            mp.Process(target=self.__processLineage,
                       args=(metadata, ubiquityThreshold, singleCopyThreshold,
                             minGenomes, workerQueue, writerQueue))
            for _ in range(numThreads)
        ]
        writeProc = mp.Process(target=self.__storeResults,
                               args=(outputFile, len(lineages), writerQueue))

        writeProc.start()

        for p in calcProc:
            p.start()

        for p in calcProc:
            p.join()

        writerQueue.put((None, None, None, None))
        writeProc.join()
Esempio n. 15
0
    def run(self):
        img = IMG()
        markerset = MarkerSet()

        print 'Reading metadata.'
        metadata = img.genomeMetadata('Final')

        print 'Getting marker genes.'
        pfamMarkers, tigrMarkers = markerset.getLineageMarkerGenes('Archaea')
        markerGenes = pfamMarkers.union(tigrMarkers)
        print '  Marker genes: ' + str(len(markerGenes))

        print 'Getting genomes of interest.'
        genomeIds = img.genomeIdsByTaxonomy('Archaea', 'Final')
        print '  Genomes: ' + str(len(genomeIds))

        print 'Getting position of each marker gene.'
        geneDistTable = img.geneDistTable(genomeIds, markerGenes)

        spearmanValues = []
        pearsonValues = []
        genomeIds = list(genomeIds)
        for i in xrange(0, len(genomeIds)):
            print str(i+1) + ' of ' + str(len(genomeIds))

            geneOrderI = []
            maskI = []
            for markerGenesId in markerGenes:
                if markerGenesId in geneDistTable[genomeIds[i]]:
                    geneOrderI.append(float(geneDistTable[genomeIds[i]][markerGenesId][0][0]) / metadata[genomeIds[i]]['genome size'])
                    maskI.append(0)
                else:
                    geneOrderI.append(-1)
                    maskI.append(1)


            for j in xrange(i+1, len(genomeIds)):
                geneOrderJ = []
                maskJ = []
                for markerGenesId in markerGenes:
                    if markerGenesId in geneDistTable[genomeIds[j]]:
                        geneOrderJ.append(float(geneDistTable[genomeIds[j]][markerGenesId][0][0]) / metadata[genomeIds[j]]['genome size'])
                        maskJ.append(0)
                    else:
                        geneOrderJ.append(-1)
                        maskJ.append(1)

                # test all translations
                bestSpearman = 0
                bestPearson = 0
                for _ in xrange(0, len(markerGenes)):
                    maskedI = []
                    maskedJ = []
                    for k in xrange(0, len(maskI)):
                        if maskI[k] == 0 and maskJ[k] == 0:
                            maskedI.append(geneOrderI[k])
                            maskedJ.append(geneOrderJ[k])
                    r, _ = spearmanr(maskedI, maskedJ)
                    if abs(r) > bestSpearman:
                        bestSpearman = abs(r)

                    r, _ = pearsonr(maskedI, maskedJ)
                    if abs(r) > bestPearson:
                        bestPearson = abs(r)

                    geneOrderJ = geneOrderJ[1:] + [geneOrderJ[0]]
                    maskJ = maskJ[1:] + [maskJ[0]]

                spearmanValues.append(bestSpearman)
                pearsonValues.append(bestPearson)

        print 'Spearman: %.2f +/- %.2f: ' % (mean(spearmanValues), std(spearmanValues))
        print 'Pearson: %.2f +/- %.2f: ' % (mean(pearsonValues), std(pearsonValues))
    def run(self, ubiquityThreshold, singleCopyThreshold, minGenomes,
            mostSpecificRank, minMarkers, completenessThreshold,
            contaminationThreshold):
        print 'Ubiquity threshold: ' + str(ubiquityThreshold)
        print 'Single-copy threshold: ' + str(singleCopyThreshold)
        print 'Min. genomes: ' + str(minGenomes)
        print 'Most specific taxonomic rank: ' + str(mostSpecificRank)
        print 'Min markers: ' + str(minMarkers)
        print 'Completeness threshold: ' + str(completenessThreshold)
        print 'Contamination threshold: ' + str(contaminationThreshold)

        img = IMG()
        markerset = MarkerSet()

        lineages = img.lineagesByCriteria(minGenomes, mostSpecificRank)

        degenerateGenomes = {}
        for lineage in lineages:
            genomeIds = img.genomeIdsByTaxonomy(lineage, 'Final')

            print ''
            print 'Lineage ' + lineage + ' contains ' + str(
                len(genomeIds)) + ' genomes.'

            # get table of PFAMs and do some initial filtering to remove PFAMs that are
            # clearly not going to pass the ubiquity and single-copy thresholds
            countTable = img.countTable(genomeIds)
            countTable = img.filterTable(genomeIds, countTable,
                                         ubiquityThreshold * 0.9,
                                         singleCopyThreshold * 0.9)

            markerGenes = markerset.markerGenes(
                genomeIds, countTable, ubiquityThreshold * len(genomeIds),
                singleCopyThreshold * len(genomeIds))
            if len(markerGenes) < minMarkers:
                continue

            geneDistTable = img.geneDistTable(genomeIds,
                                              markerGenes,
                                              spacingBetweenContigs=1e6)
            colocatedGenes = markerset.colocatedGenes(geneDistTable)
            colocatedSets = markerset.colocatedSets(colocatedGenes,
                                                    markerGenes)

            for genomeId in genomeIds:
                completeness, contamination = markerset.genomeCheck(
                    colocatedSets, genomeId, countTable)

                if completeness < completenessThreshold or contamination > contaminationThreshold:
                    degenerateGenomes[genomeId] = degenerateGenomes.get(
                        genomeId, []) + [[
                            lineage.split(';')[-1].strip(),
                            len(genomeIds),
                            len(colocatedSets), completeness, contamination
                        ]]

        # write out degenerate genomes
        metadata = img.genomeMetadata('Final')

        fout = open('./data/degenerate_genomes.tsv', 'w')
        fout.write(
            'Genome Id\tTaxonomy\tGenome Size (Gbps)\tScaffolds\tBiotic Relationships\tStatus\tLineage\t# genomes\tMarker set size\tCompleteness\tContamination\n'
        )
        for genomeId, data in degenerateGenomes.iteritems():
            fout.write(genomeId + '\t' +
                       '; '.join(metadata[genomeId]['taxonomy']) + '\t%.2f' %
                       (float(metadata[genomeId]['genome size']) / 1e6) +
                       '\t' + str(metadata[genomeId]['scaffold count']))
            fout.write('\t' + metadata[genomeId]['biotic relationships'] +
                       '\t' + metadata[genomeId]['status'])

            for d in data:
                fout.write('\t' + d[0] + '\t' + str(d[1]) + '\t' + str(d[2]) +
                           '\t%.3f\t%.3f' % (d[3], d[4]))
            fout.write('\n')

        fout.close()
    def run(self, ubiquityThreshold, singleCopyThreshold, trustedCompleteness, trustedContamination, genomeCompleteness, genomeContamination):
        img = IMG()
        markerset = MarkerSet()

        metadata = img.genomeMetadata()

        trustedOut = open('./data/trusted_genomes.tsv', 'w')
        trustedOut.write('Genome Id\tLineage\tGenome size (Mbps)\tScaffold count\tBiotic Relationship\tStatus\tCompleteness\tContamination\n')

        filteredOut = open('./data/filtered_genomes.tsv', 'w')
        filteredOut.write('Genome Id\tLineage\tGenome size (Mbps)\tScaffold count\tBiotic Relationship\tStatus\tCompleteness\tContamination\n')

        allGenomeIds = set()
        allTrustedGenomeIds = set()
        for lineage in ['Archaea', 'Bacteria']:
            # get all genomes in lineage and build gene count table
            print '\nBuilding gene count table.'
            allLineageGenomeIds = img.genomeIdsByTaxonomy(lineage, metadata, 'All')
            countTable = img.countTable(allLineageGenomeIds)
            countTable = img.filterTable(allLineageGenomeIds, countTable, 0.9*ubiquityThreshold, 0.9*singleCopyThreshold)

            # get all genomes from specific lineage
            allGenomeIds = allGenomeIds.union(allLineageGenomeIds)

            print 'Lineage ' + lineage + ' contains ' + str(len(allLineageGenomeIds)) + ' genomes.'

            # tabulate genomes from each phylum
            allPhylumCounts = {}
            for genomeId in allLineageGenomeIds:
                taxon = metadata[genomeId]['taxonomy'][1]
                allPhylumCounts[taxon] = allPhylumCounts.get(taxon, 0) + 1

            # identify marker set for genomes
            markerGenes = markerset.markerGenes(allLineageGenomeIds, countTable, ubiquityThreshold*len(allLineageGenomeIds), singleCopyThreshold*len(allLineageGenomeIds))
            print '  Marker genes: ' + str(len(markerGenes))

            geneDistTable = img.geneDistTable(allLineageGenomeIds, markerGenes, spacingBetweenContigs=1e6)
            colocatedGenes = markerset.colocatedGenes(geneDistTable, metadata)
            colocatedSets = markerset.colocatedSets(colocatedGenes, markerGenes)
            print '  Marker set size: ' + str(len(colocatedSets))

            # identifying trusted genomes (highly complete, low contamination genomes)
            trustedGenomeIds = set()
            for genomeId in allLineageGenomeIds:
                completeness, contamination = markerset.genomeCheck(colocatedSets, genomeId, countTable)

                if completeness >= trustedCompleteness and contamination <= trustedContamination:
                    trustedGenomeIds.add(genomeId)
                    allTrustedGenomeIds.add(genomeId)

                    trustedOut.write(genomeId + '\t' + '; '.join(metadata[genomeId]['taxonomy']))
                    trustedOut.write('\t%.2f' % (float(metadata[genomeId]['genome size']) / 1e6))
                    trustedOut.write('\t' + str(metadata[genomeId]['scaffold count']))
                    trustedOut.write('\t' + metadata[genomeId]['biotic relationships'])
                    trustedOut.write('\t' + metadata[genomeId]['status'])
                    trustedOut.write('\t%.3f\t%.3f' % (completeness, contamination) + '\n')
                else:
                    filteredOut.write(genomeId + '\t' + '; '.join(metadata[genomeId]['taxonomy']))
                    filteredOut.write('\t%.2f' % (float(metadata[genomeId]['genome size']) / 1e6))
                    filteredOut.write('\t' + str(metadata[genomeId]['scaffold count']))
                    filteredOut.write('\t' + metadata[genomeId]['biotic relationships'])
                    filteredOut.write('\t' + metadata[genomeId]['status'])
                    filteredOut.write('\t%.3f\t%.3f' % (completeness, contamination) + '\n')

            print '  Trusted genomes: ' + str(len(trustedGenomeIds))

            # determine status of trusted genomes
            statusBreakdown = {}
            for genomeId in trustedGenomeIds:
                statusBreakdown[metadata[genomeId]['status']] = statusBreakdown.get(metadata[genomeId]['status'], 0) + 1

            print '  Trusted genome status breakdown: '
            for status, count in statusBreakdown.iteritems():
                print '    ' + status + ': ' + str(count)

            # determine status of retained genomes
            proposalNameBreakdown = {}
            for genomeId in trustedGenomeIds:
                proposalNameBreakdown[metadata[genomeId]['proposal name']] = proposalNameBreakdown.get(metadata[genomeId]['proposal name'], 0) + 1

            print '  Retained genome proposal name breakdown: '
            for pn, count in proposalNameBreakdown.iteritems():
                if 'KMG' in pn or 'GEBA' in pn or 'HMP' in pn:
                    print '    ' + pn + ': ' + str(count)

            print '  Filtered genomes by phylum:'
            trustedPhylumCounts = {}
            for genomeId in trustedGenomeIds:
                taxon = metadata[genomeId]['taxonomy'][1]
                trustedPhylumCounts[taxon] = trustedPhylumCounts.get(taxon, 0) + 1

            for phylum, count in allPhylumCounts.iteritems():
                print phylum + ': %d of %d' % (trustedPhylumCounts.get(phylum, 0), count)

        trustedOut.close()
        filteredOut.close()

        # write out lineage statistics for genome distribution
        allStats = {}
        trustedStats = {}

        for r in xrange(0, 6): # Domain to Genus
            for genomeId, data in metadata.iteritems():
                taxaStr = '; '.join(data['taxonomy'][0:r+1])
                allStats[taxaStr] = allStats.get(taxaStr, 0) + 1
                if genomeId in allTrustedGenomeIds:
                    trustedStats[taxaStr] = trustedStats.get(taxaStr, 0) + 1

        sortedLineages = img.lineagesSorted()

        fout = open('./data/lineage_stats.tsv', 'w')
        fout.write('Lineage\tGenomes with metadata\tTrusted genomes\n')
        for lineage in sortedLineages:
            fout.write(lineage + '\t' + str(allStats.get(lineage, 0))+ '\t' + str(trustedStats.get(lineage, 0))+ '\n')
        fout.close()
Esempio n. 18
0
    def run(self):
        img = IMG()
        markerset = MarkerSet()

        print('Reading metadata.')
        metadata = img.genomeMetadata('Final')

        print('Getting marker genes.')
        pfamMarkers, tigrMarkers = markerset.getLineageMarkerGenes('Archaea')
        markerGenes = pfamMarkers.union(tigrMarkers)
        print('  Marker genes: ' + str(len(markerGenes)))

        print('Getting genomes of interest.')
        genomeIds = img.genomeIdsByTaxonomy('Archaea', 'Final')
        print('  Genomes: ' + str(len(genomeIds)))

        print('Getting position of each marker gene.')
        geneDistTable = img.geneDistTable(genomeIds,
                                          markerGenes,
                                          spacingBetweenContigs=1e6)

        spearmanValues = []
        pearsonValues = []
        genomeIds = list(genomeIds)
        for i in range(0, len(genomeIds)):
            print(str(i + 1) + ' of ' + str(len(genomeIds)))

            geneOrderI = []
            maskI = []
            for markerGenesId in markerGenes:
                if markerGenesId in geneDistTable[genomeIds[i]]:
                    geneOrderI.append(
                        float(geneDistTable[genomeIds[i]][markerGenesId][0][0])
                        / metadata[genomeIds[i]]['genome size'])
                    maskI.append(0)
                else:
                    geneOrderI.append(-1)
                    maskI.append(1)

            for j in range(i + 1, len(genomeIds)):
                geneOrderJ = []
                maskJ = []
                for markerGenesId in markerGenes:
                    if markerGenesId in geneDistTable[genomeIds[j]]:
                        geneOrderJ.append(
                            float(geneDistTable[genomeIds[j]][markerGenesId][0]
                                  [0]) / metadata[genomeIds[j]]['genome size'])
                        maskJ.append(0)
                    else:
                        geneOrderJ.append(-1)
                        maskJ.append(1)

                # test all translations
                bestSpearman = 0
                bestPearson = 0
                for _ in range(0, len(markerGenes)):
                    maskedI = []
                    maskedJ = []
                    for k in range(0, len(maskI)):
                        if maskI[k] == 0 and maskJ[k] == 0:
                            maskedI.append(geneOrderI[k])
                            maskedJ.append(geneOrderJ[k])
                    r, _ = spearmanr(maskedI, maskedJ)
                    if abs(r) > bestSpearman:
                        bestSpearman = abs(r)

                    r, _ = pearsonr(maskedI, maskedJ)
                    if abs(r) > bestPearson:
                        bestPearson = abs(r)

                    geneOrderJ = geneOrderJ[1:] + [geneOrderJ[0]]
                    maskJ = maskJ[1:] + [maskJ[0]]

                spearmanValues.append(bestSpearman)
                pearsonValues.append(bestPearson)

        print('Spearman: %.2f +/- %.2f: ' %
              (mean(spearmanValues), std(spearmanValues)))
        print('Pearson: %.2f +/- %.2f: ' %
              (mean(pearsonValues), std(pearsonValues)))
Esempio n. 19
0
    def run(self, taxonomyStr, ubiquityThreshold, singleCopyThreshold, numBins,
            numRndGenomes):
        img = IMG()
        markerSet = MarkerSet()

        metadata = img.genomeMetadata()
        lineageGenomeIds = img.genomeIdsByTaxonomy(taxonomyStr, metadata)

        # build marker set from finished prokaryotic genomes
        genomeIds = []
        for genomeId in lineageGenomeIds:
            if metadata[genomeId]['status'] == 'Finished' and (
                    metadata[genomeId]['taxonomy'][0] == 'Bacteria'
                    or metadata[genomeId]['taxonomy'][0] == 'Archaea'):
                genomeIds.append(genomeId)
        genomeIds = set(genomeIds) - img.genomesWithMissingData(genomeIds)

        print 'Lineage ' + taxonomyStr + ' contains ' + str(
            len(genomeIds)) + ' genomes.'

        # get marker set
        countTable = img.countTable(genomeIds)
        countTable = img.filterTable(genomeIds, countTable,
                                     0.9 * ubiquityThreshold,
                                     0.9 * singleCopyThreshold)
        markerGenes = markerSet.markerGenes(
            genomeIds, countTable, ubiquityThreshold * len(genomeIds),
            singleCopyThreshold * len(genomeIds))
        tigrToRemove = img.identifyRedundantTIGRFAMs(markerGenes)
        markerGenes = markerGenes - tigrToRemove
        geneDistTable = img.geneDistTable(genomeIds,
                                          markerGenes,
                                          spacingBetweenContigs=1e6)

        print 'Number of marker genes: ' + str(len(markerGenes))

        # randomly set genomes to plot
        if numRndGenomes != -1:
            genomeIds = random.sample(list(genomeIds), numRndGenomes)
        genomeIds = set(genomeIds)

        # plot distribution of marker genes
        filename = 'geneDistribution.' + taxonomyStr.replace(
            ';', '_') + '.' + str(ubiquityThreshold) + '-' + str(
                singleCopyThreshold) + '.tsv'
        fout = open(filename, 'w')
        fout.write(
            'Genome ID\tLineage\tNumber of Genes\tUniformity\tDistribution\n')
        matrix = []
        rowLabels = []
        for genomeId in genomeIds:
            binSize = float(metadata[genomeId]['genome size']) / numBins

            binCounts = [0] * numBins
            pts = []
            for _, data in geneDistTable[genomeId].iteritems():
                for genePos in data:
                    binNum = int(genePos[1] / binSize)
                    binCounts[binNum] += 1
                    pts.append(genePos[1])
            matrix.append(binCounts)

            u = markerSet.uniformity(metadata[genomeId]['genome size'], pts)

            fout.write(genomeId + '\t' +
                       '; '.join(metadata[genomeId]['taxonomy']) + '\t' +
                       str(len(geneDistTable[genomeId])) + '\t%.3f' % u)
            for b in xrange(0, numBins):
                fout.write('\t' + str(binCounts[b]))
            fout.write('\n')

            rowLabels.append('%.2f' % u + ', ' + str(genomeId) + ' - ' +
                             '; '.join(metadata[genomeId]['taxonomy'][0:5]))

        fout.close()

        # plot data
        heatmap = Heatmap()
        plotFilename = 'geneDistribution.' + taxonomyStr.replace(
            ';', '_') + '.' + str(ubiquityThreshold) + '-' + str(
                singleCopyThreshold) + '.png'
        heatmap.plot(plotFilename, matrix, rowLabels, 0.6)
Esempio n. 20
0
class MarkerSetStabilityTest(object):
    def __init__(self):
        self.img = IMG()
        self.markerset = MarkerSet()

    def __processLineage(self, metadata, ubiquityThreshold, singleCopyThreshold, minGenomes, queueIn, queueOut):
        """Assess stability of marker set for a specific named taxonomic group."""
        while True:
            lineage = queueIn.get(block=True, timeout=None) 
            if lineage == None:
                break  
            
            genomeIds = self.img.genomeIdsByTaxonomy(lineage, metadata, 'trusted')
            
            markerGenes = []
            perChange = []
            numGenomesToSelect = int(0.9*len(genomeIds))
            if len(genomeIds) >= minGenomes:  
                # calculate marker set for all genomes in lineage          
                geneCountTable = self.img.geneCountTable(genomeIds)
                markerGenes = self.markerset.markerGenes(genomeIds, geneCountTable, ubiquityThreshold*len(genomeIds), singleCopyThreshold*len(genomeIds))
                tigrToRemove = self.img.identifyRedundantTIGRFAMs(markerGenes)

                markerGenes = markerGenes - tigrToRemove

                for _ in xrange(0, 100):
                    # calculate marker set for subset of genomes
                    subsetGenomeIds = random.sample(genomeIds, numGenomesToSelect)
                    geneCountTable = self.img.geneCountTable(subsetGenomeIds)
                    subsetMarkerGenes = self.markerset.markerGenes(subsetGenomeIds, geneCountTable, ubiquityThreshold*numGenomesToSelect, singleCopyThreshold*numGenomesToSelect)
                    tigrToRemove = self.img.identifyRedundantTIGRFAMs(subsetMarkerGenes)
                    subsetMarkerGenes = subsetMarkerGenes - tigrToRemove

                    perChange.append(float(len(markerGenes.symmetric_difference(subsetMarkerGenes)))*100.0 / len(markerGenes))

            if perChange != []:
                queueOut.put((lineage, len(genomeIds), len(markerGenes), numGenomesToSelect, mean(perChange), std(perChange)))
            else:
                queueOut.put((lineage, len(genomeIds), len(markerGenes), numGenomesToSelect, -1, -1))
                
    def __storeResults(self, outputFile, totalLineages, writerQueue):
        """Store results to file."""
        
        fout = open(outputFile, 'w')
        fout.write('Lineage\t# genomes\t# markers\t# sampled genomes\tmean % change\tstd % change\n')

        numProcessedLineages = 0
        while True:
            lineage, numGenomes, numMarkerGenes, numSampledGenomes, meanPerChange, stdPerChange = writerQueue.get(block=True, timeout=None)
            if lineage == None:
                break
                    
            numProcessedLineages += 1
            statusStr = '    Finished processing %d of %d (%.2f%%) lineages.' % (numProcessedLineages, totalLineages, float(numProcessedLineages)*100/totalLineages)
            sys.stdout.write('%s\r' % statusStr)
            sys.stdout.flush()
            

            fout.write('%s\t%d\t%d\t%d\t%f\t%f\n' % (lineage, numGenomes, numMarkerGenes, numSampledGenomes, meanPerChange, stdPerChange))

        sys.stdout.write('\n')
            
        fout.close()
        
        
    def run(self, outputFile, ubiquityThreshold, singleCopyThreshold, minGenomes, mostSpecificRank, numThreads):
        """Calculate stability of marker sets for named taxonomic groups."""  
        
        print '  Testing stability of marker sets:'
        
        random.seed(1)
        
        # process each sequence in parallel
        workerQueue = mp.Queue()
        writerQueue = mp.Queue()

        metadata = self.img.genomeMetadata()
        lineages = self.img.lineagesByCriteria(metadata, minGenomes, mostSpecificRank)

        for lineage in lineages:
            workerQueue.put(lineage)

        for _ in range(numThreads):
            workerQueue.put(None)
 
        calcProc = [mp.Process(target = self.__processLineage, args = (metadata, ubiquityThreshold, singleCopyThreshold, minGenomes, workerQueue, writerQueue)) for _ in range(numThreads)]
        writeProc = mp.Process(target = self.__storeResults, args = (outputFile, len(lineages), writerQueue))

        writeProc.start()

        for p in calcProc:
            p.start()

        for p in calcProc:
            p.join()

        writerQueue.put((None, None, None, None, None, None))
        writeProc.join()
Esempio n. 21
0
class MarkerSetStabilityTest(object):
    def __init__(self):
        self.img = IMG()
        self.markerset = MarkerSet()

    def __processLineage(self, metadata, ubiquityThreshold,
                         singleCopyThreshold, minGenomes, queueIn, queueOut):
        """Assess stability of marker set for a specific named taxonomic group."""
        while True:
            lineage = queueIn.get(block=True, timeout=None)
            if lineage == None:
                break

            genomeIds = self.img.genomeIdsByTaxonomy(lineage, metadata,
                                                     'trusted')

            markerGenes = []
            perChange = []
            numGenomesToSelect = int(0.9 * len(genomeIds))
            if len(genomeIds) >= minGenomes:
                # calculate marker set for all genomes in lineage
                geneCountTable = self.img.geneCountTable(genomeIds)
                markerGenes = self.markerset.markerGenes(
                    genomeIds, geneCountTable,
                    ubiquityThreshold * len(genomeIds),
                    singleCopyThreshold * len(genomeIds))
                tigrToRemove = self.img.identifyRedundantTIGRFAMs(markerGenes)

                markerGenes = markerGenes - tigrToRemove

                for _ in range(0, 100):
                    # calculate marker set for subset of genomes
                    subsetGenomeIds = random.sample(genomeIds,
                                                    numGenomesToSelect)
                    geneCountTable = self.img.geneCountTable(subsetGenomeIds)
                    subsetMarkerGenes = self.markerset.markerGenes(
                        subsetGenomeIds, geneCountTable,
                        ubiquityThreshold * numGenomesToSelect,
                        singleCopyThreshold * numGenomesToSelect)
                    tigrToRemove = self.img.identifyRedundantTIGRFAMs(
                        subsetMarkerGenes)
                    subsetMarkerGenes = subsetMarkerGenes - tigrToRemove

                    perChange.append(
                        float(
                            len(
                                markerGenes.symmetric_difference(
                                    subsetMarkerGenes))) * 100.0 /
                        len(markerGenes))

            if perChange != []:
                queueOut.put(
                    (lineage, len(genomeIds), len(markerGenes),
                     numGenomesToSelect, mean(perChange), std(perChange)))
            else:
                queueOut.put((lineage, len(genomeIds), len(markerGenes),
                              numGenomesToSelect, -1, -1))

    def __storeResults(self, outputFile, totalLineages, writerQueue):
        """Store results to file."""

        fout = open(outputFile, 'w')
        fout.write(
            'Lineage\t# genomes\t# markers\t# sampled genomes\tmean % change\tstd % change\n'
        )

        numProcessedLineages = 0
        while True:
            lineage, numGenomes, numMarkerGenes, numSampledGenomes, meanPerChange, stdPerChange = writerQueue.get(
                block=True, timeout=None)
            if lineage == None:
                break

            numProcessedLineages += 1
            statusStr = '    Finished processing %d of %d (%.2f%%) lineages.' % (
                numProcessedLineages, totalLineages,
                float(numProcessedLineages) * 100 / totalLineages)
            sys.stdout.write('%s\r' % statusStr)
            sys.stdout.flush()

            fout.write('%s\t%d\t%d\t%d\t%f\t%f\n' %
                       (lineage, numGenomes, numMarkerGenes, numSampledGenomes,
                        meanPerChange, stdPerChange))

        sys.stdout.write('\n')

        fout.close()

    def run(self, outputFile, ubiquityThreshold, singleCopyThreshold,
            minGenomes, mostSpecificRank, numThreads):
        """Calculate stability of marker sets for named taxonomic groups."""

        print('  Testing stability of marker sets:')

        random.seed(1)

        # process each sequence in parallel
        workerQueue = mp.Queue()
        writerQueue = mp.Queue()

        metadata = self.img.genomeMetadata()
        lineages = self.img.lineagesByCriteria(metadata, minGenomes,
                                               mostSpecificRank)

        for lineage in lineages:
            workerQueue.put(lineage)

        for _ in range(numThreads):
            workerQueue.put(None)

        calcProc = [
            mp.Process(target=self.__processLineage,
                       args=(metadata, ubiquityThreshold, singleCopyThreshold,
                             minGenomes, workerQueue, writerQueue))
            for _ in range(numThreads)
        ]
        writeProc = mp.Process(target=self.__storeResults,
                               args=(outputFile, len(lineages), writerQueue))

        writeProc.start()

        for p in calcProc:
            p.start()

        for p in calcProc:
            p.join()

        writerQueue.put((None, None, None, None, None, None))
        writeProc.join()
Esempio n. 22
0
 def __init__(self):
     self.img = IMG()
     self.markerset = MarkerSet()
Esempio n. 23
0
class MarkerSetStability(object):
    def __init__(self):
        self.img = IMG()
        self.markerset = MarkerSet()

    def __processLineage(self, metadata, ubiquityThreshold, singleCopyThreshold, minGenomes, queueIn, queueOut):
        """Assess stability of marker set for a specific named taxonomic group."""
        while True:
            lineage = queueIn.get(block=True, timeout=None) 
            if lineage == None:
                break  
            
            genomeIds = self.img.genomeIdsByTaxonomy(lineage, metadata, 'trusted')
            
            changeMarkerSetSize = {}
            markerGenes = []
            if len(genomeIds) >= minGenomes:  
                # calculate marker set for all genomes in lineage          
                geneCountTable = self.img.geneCountTable(genomeIds)
                markerGenes = self.markerset.markerGenes(genomeIds, geneCountTable, ubiquityThreshold*len(genomeIds), singleCopyThreshold*len(genomeIds))
                tigrToRemove = self.img.identifyRedundantTIGRFAMs(markerGenes)
                markerGenes = markerGenes - tigrToRemove
     
                for selectPer in xrange(50, 101, 5):
                    numGenomesToSelect = int(float(selectPer)/100 * len(genomeIds))
                    perChange = []
                    for _ in xrange(0, 10):
                        # calculate marker set for subset of genomes
                        subsetGenomeIds = random.sample(genomeIds, numGenomesToSelect)
                        geneCountTable = self.img.geneCountTable(subsetGenomeIds)
                        subsetMarkerGenes = self.markerset.markerGenes(subsetGenomeIds, geneCountTable, ubiquityThreshold*numGenomesToSelect, singleCopyThreshold*numGenomesToSelect)
                        tigrToRemove = self.img.identifyRedundantTIGRFAMs(subsetMarkerGenes)
                        subsetMarkerGenes = subsetMarkerGenes - tigrToRemove
    
                        perChange.append(float(len(markerGenes.symmetric_difference(subsetMarkerGenes)))*100.0 / len(markerGenes))
    
                    changeMarkerSetSize[selectPer] = [mean(perChange), std(perChange)]  

            queueOut.put((lineage, len(genomeIds), len(markerGenes), changeMarkerSetSize))

    def __storeResults(self, outputFile, totalLineages, writerQueue):
        """Store results to file."""
        
        fout = open(outputFile, 'w')
        fout.write('Lineage\t# genomes\t# markers\tsubsample %\tmean % change\tstd % change\n')

        numProcessedLineages = 0
        while True:
            lineage, numGenomes, numMarkerGenes, changeMarkerSetSize = writerQueue.get(block=True, timeout=None)
            if lineage == None:
                break
                    
            numProcessedLineages += 1
            statusStr = '    Finished processing %d of %d (%.2f%%) lineages.' % (numProcessedLineages, totalLineages, float(numProcessedLineages)*100/totalLineages)
            sys.stdout.write('%s\r' % statusStr)
            sys.stdout.flush()
            
            for selectPer in sorted(changeMarkerSetSize.keys()): 
                fout.write('%s\t%d\t%d\t%d\t%f\t%f\n' % (lineage, numGenomes, numMarkerGenes, selectPer, changeMarkerSetSize[selectPer][0], changeMarkerSetSize[selectPer][1]))

        sys.stdout.write('\n')
            
        fout.close()
        
        
    def run(self, outputFile, ubiquityThreshold, singleCopyThreshold, minGenomes, mostSpecificRank, numThreads):
        """Calculate stability of marker sets for named taxonomic groups."""  
        
        print '  Calculating stability of marker sets:'
        
        random.seed(1)
        
        # process each sequence in parallel
        workerQueue = mp.Queue()
        writerQueue = mp.Queue()

        metadata = self.img.genomeMetadata()
        lineages = self.img.lineagesByCriteria(metadata, minGenomes, mostSpecificRank)
        
        #lineages = ['Bacteria']
        #lineages += ['Bacteria;Proteobacteria']
        #lineages += ['Bacteria;Proteobacteria;Gammaproteobacteria']
        #lineages += ['Bacteria;Proteobacteria;Gammaproteobacteria;Enterobacteriales']
        #lineages += ['Bacteria;Proteobacteria;Gammaproteobacteria;Enterobacteriales;Enterobacteriaceae']
        #lineages += ['Bacteria;Proteobacteria;Gammaproteobacteria;Enterobacteriales;Enterobacteriaceae;Escherichia']
        #lineages += ['Bacteria;Proteobacteria;Gammaproteobacteria;Enterobacteriales;Enterobacteriaceae;Escherichia;coli']
        
        #lineages = ['Archaea']
        #lineages += ['Archaea;Euryarchaeota']
        #lineages += ['Archaea;Euryarchaeota;Methanomicrobia']
        #lineages += ['Archaea;Euryarchaeota;Methanomicrobia;Methanosarcinales']
        #lineages += ['Archaea;Euryarchaeota;Methanomicrobia;Methanosarcinales;Methanosarcinaceae']

        for lineage in lineages:
            workerQueue.put(lineage)

        for _ in range(numThreads):
            workerQueue.put(None)
 
        calcProc = [mp.Process(target = self.__processLineage, args = (metadata, ubiquityThreshold, singleCopyThreshold, minGenomes, workerQueue, writerQueue)) for _ in range(numThreads)]
        writeProc = mp.Process(target = self.__storeResults, args = (outputFile, len(lineages), writerQueue))

        writeProc.start()

        for p in calcProc:
            p.start()

        for p in calcProc:
            p.join()

        writerQueue.put((None, None, None, None))
        writeProc.join()