Uses KEGG to retrieve all ids and respective ecs for a given KEGG organism

    :param organism: an organisms as listed in organismsKEGG()

    :returns: a Pandas dataframe of with 'ec' and 'KEGGid'.
495957
def ecs_idsKEGG(organism):
    
    kegg_ec=urlopen("http://rest.kegg.jp/link/"+organism+"/enzyme").read()
    kegg_ec=kegg_ec.split("\n")
    final=[]
    for k in kegg_ec:
        final.append(k.split("\t"))
    df=pd.DataFrame(final[0:len(final)-1])[[0,1]]
    df.columns=['ec','KEGGid']
    return df
184564
def get(self, name):
        
        if self.structs.has_key(name):
            return self.structs[name]
        elif self.enums.has_key(name):
            return self.enums[name]
        elif self.interfaces.has_key(name):
            return self.interfaces[name]
        else:
            raise RpcException(ERR_INVALID_PARAMS, "Unknown entity: '%s'" % name)
845456
def get_atlas_summary_df(self):
        
        all_info = []
        for g in self.reference_gempro.genes_with_a_representative_sequence:
            info = {}
            info['Gene_ID'] = g.id
            info['Gene_name'] = g.name

            # Protein object
            p = g.protein
            info['Protein_sequences'] = len(p.sequences)
            info['Protein_structures'] = len(p.structures)

            # SeqProp
            rseq = p.representative_sequence
            info['RepSeq_ID'] = rseq.id
            info['RepSeq_sequence_length'] = rseq.seq_len
            info['RepSeq_num_sequence_alignments'] = len([x for x in p.sequence_alignments if x.annotations['ssbio_type'] == 'seqalign'])
            info['RepSeq_num_structure_alignments'] = len([x for x in p.sequence_alignments if x.annotations['ssbio_type'] == 'structalign'])

            # SeqRecord annotations (properties calculated that summarize the whole sequence)
            for annotation_name, annotation in rseq.annotations.items():
                info['RepSeq_' + annotation_name] = annotation

            # SeqRecord alignment annotations
            all_num_mutations = []
            all_num_deletions = []
            all_len_deletions = []
            all_num_insertions = []
            all_len_insertions = []
            all_percent_identity = []
            all_percent_similarity = []
            for aln in p.sequence_alignments:
                # Gather the strain speicific stuff
                if '{}_'.format(p.id) not in aln.annotations['b_seq']:
                    continue
                info[aln.annotations['b_seq'].split('{}_'.format(p.id))[1]] = aln.annotations['percent_identity']

                # Gather the percent identities/similarities
                all_percent_identity.append(aln.annotations['percent_identity'])
                all_percent_similarity.append(aln.annotations['percent_similarity'])

                # Gather the number of residues that are mutated (filter for different mutations of same residue)
                num_mutations = len(list(set([x[1] for x in aln.annotations['mutations']])))
                all_num_mutations.append(num_mutations)

                # Gather the number of deletions as well as the length of the deletion
                if not aln.annotations['deletions']:
                    num_deletions = 0
                    len_deletions = [0]
                else:
                    num_deletions = len(aln.annotations['deletions'])
                    len_deletions = [x[1] for x in aln.annotations['deletions']]
                all_num_deletions.append(num_deletions)
                # Get the total length of the deletion for this one strain
                avg_len_deletions = np.sum(len_deletions)
                all_len_deletions.append(avg_len_deletions)

                # Gather the number of insertions as well as the length of the insertion
                if not aln.annotations['insertions']:
                    num_insertions = 0
                    len_insertions = [0]
                else:
                    num_insertions = len(aln.annotations['insertions'])
                    len_insertions = [x[1] for x in aln.annotations['insertions']]
                all_num_insertions.append(num_insertions)
                # Get the total length of insertion for this one strain
                avg_len_insertions = np.sum(len_insertions)
                all_len_insertions.append(avg_len_insertions)

            info['ATLAS_mean_num_mutations'] = np.mean(all_num_mutations)
            info['ATLAS_mean_num_deletions'] = np.mean(all_num_deletions)
            info['ATLAS_mean_len_deletions'] = np.mean(all_len_deletions)
            info['ATLAS_mean_num_insertions'] = np.mean(all_num_insertions)
            info['ATLAS_mean_len_insertions'] = np.mean(all_len_insertions)
            info['ATLAS_mean_percent_identity'] = np.mean(all_percent_identity)
            info['ATLAS_mean_percent_similarity'] = np.mean(all_percent_similarity)

            # Other mutation analysis
            single, fingerprint = p.sequence_mutation_summary()

            # Mutations that show up in more than 10% of strains
            singles = []
            for k, v in single.items():
                k = [str(x) for x in k]
                if len(v) / len(p.sequence_alignments) >= 0.01:
                    singles.append(''.join(k))  # len(v) is the number of strains which have this mutation
            info['ATLAS_popular_mutations'] = ';'.join(singles)

            # Mutation groups that show up in more than 10% of strains
            allfingerprints = []
            for k, v in fingerprint.items():
                if len(v) / len(p.sequence_alignments) >= 0.01:
                    fingerprints = []
                    for m in k:
                        y = [str(x) for x in m]
                        fingerprints.append(''.join(y))
                    allfingerprints.append('-'.join(fingerprints))
            info['ATLAS_popular_mutation_groups'] = ';'.join(allfingerprints)

            # StructProp
            rstruct = p.representative_structure
            if rstruct:
                if rstruct.structure_file:
                    info['RepStruct_ID'] = rstruct.id
                    info['RepStruct_is_experimental'] = rstruct.is_experimental
                    info['RepStruct_description'] = rstruct.description
                    info['RepStruct_repseq_coverage'] = p.representative_chain_seq_coverage

                    # ChainProp
                    rchain = p.representative_chain
                    info['RepChain_ID'] = rchain

                    # ChainProp SeqRecord annotations
                    rchain_sr = rstruct.chains.get_by_id(rchain).seq_record
                    for annotation_name, annotation in rchain_sr.annotations.items():
                        info['RepChain_' + annotation_name] = annotation

            all_info.append(info)

        cols = ['Gene_ID', 'Gene_name', 'Protein_sequences', 'Protein_structures',
                'RepSeq_ID', 'RepSeq_sequence_length',
                'RepSeq_num_sequence_alignments', 'RepSeq_num_structure_alignments',
                'RepStruct_ID', 'RepChain_ID', 'RepStruct_description',
                'RepStruct_is_experimental', 'RepStruct_repseq_coverage',
                'ATLAS_mean_percent_identity', 'ATLAS_mean_percent_similarity', 'ATLAS_mean_num_mutations',
                'ATLAS_popular_mutations', 'ATLAS_popular_mutation_groups', 'ATLAS_mean_num_deletions',
                'ATLAS_mean_num_insertions', 'ATLAS_mean_len_deletions', 'ATLAS_mean_len_insertions',
                'RepSeq_aromaticity', 'RepSeq_instability_index', 'RepSeq_isoelectric_point', 'RepSeq_molecular_weight',
                'RepSeq_monoisotopic', 'RepSeq_num_tm_helix-tmhmm', 'RepSeq_percent_acidic', 'RepSeq_percent_aliphatic',
                'RepSeq_percent_aromatic', 'RepSeq_percent_B-sspro8', 'RepSeq_percent_basic',
                'RepSeq_percent_buried-accpro', 'RepSeq_percent_buried-accpro20', 'RepSeq_percent_C-sspro',
                'RepSeq_percent_C-sspro8', 'RepSeq_percent_charged', 'RepSeq_percent_E-sspro',
                'RepSeq_percent_E-sspro8', 'RepSeq_percent_exposed-accpro', 'RepSeq_percent_exposed-accpro20',
                'RepSeq_percent_G-sspro8', 'RepSeq_percent_H-sspro', 'RepSeq_percent_H-sspro8',
                'RepSeq_percent_helix_naive', 'RepSeq_percent_I-sspro8', 'RepSeq_percent_non-polar',
                'RepSeq_percent_polar', 'RepSeq_percent_S-sspro8', 'RepSeq_percent_small',
                'RepSeq_percent_strand_naive', 'RepSeq_percent_T-sspro8', 'RepSeq_percent_tiny',
                'RepSeq_percent_turn_naive', 'RepChain_percent_B-dssp', 'RepChain_percent_C-dssp',
                'RepChain_percent_E-dssp', 'RepChain_percent_G-dssp', 'RepChain_percent_H-dssp',
                'RepChain_percent_I-dssp', 'RepChain_percent_S-dssp', 'RepChain_percent_T-dssp',
                'RepChain_SSBOND-biopython']
        cols.extend([x.id for x in self.strains])

        df_atlas_summary = pd.DataFrame(all_info, columns=cols)
        # Drop columns that don't have anything in them
        df_atlas_summary.dropna(axis=1, how='all', inplace=True)

        return df_atlas_summary
909589
def find_enriched(sample_entities=None,
                  background_entities=None,
                  object_category=None,
                  **kwargs):

    
    if sample_entities is None:
        sample_entites = []

    (sample_counts, sample_results) = get_counts(entities=sample_entities,
                                                 object_category=object_category,
                                                 min_count=2,
                                                 **kwargs)
    print(str(sample_counts))

    sample_fcs = sample_results['facet_counts']
    taxon_count_dict = sample_fcs[M.SUBJECT_TAXON]

    taxon=None
    for (t,tc) in taxon_count_dict.items():
        # TODO - throw error if multiple taxa
        taxon = t

    if background_entities is None:
        objects = list(sample_counts.keys())
        print("OBJECTS="+str(objects))
        background_entities = get_background(objects, taxon, object_category)

    # TODO: consider caching
    (bg_counts,_) = get_counts(entities=background_entities,
                               object_category=object_category,
                               **kwargs)

    sample_n = len(sample_entities) # TODO - annotated only?
    pop_n = len(background_entities)
    # adapted from goatools
    for (sample_termid,sample_count) in sample_counts.items():
        pop_count = bg_counts[sample_termid]

        # https://en.wikipedia.org/wiki/Fisher's_exact_test
        #              Cls  NotCls
        # study/sample [a,      b]
        # rest of ref  [c,      d]
        #              
        a = sample_count
        b = sample_n - sample_count
        c = pop_count - sample_count
        d = pop_n - pop_count - b
        print("ABCD="+str((sample_termid,a,b,c,d,sample_n)))
        _, p_uncorrected = sp.stats.fisher_exact( [[a, b], [c, d]])
        print("P="+str(p_uncorrected))
1359920
def get_ec_numbers(cls, entry):
        
        ec_numbers = []

        for ec in entry.iterfind("./protein/recommendedName/ecNumber"):
            ec_numbers.append(models.ECNumber(ec_number=ec.text))
        return ec_numbers
944690
def _get_chrbands(self, limit, taxon):
        

        if limit is None:
            limit = sys.maxsize   # practical limit anyway
        model = Model(self.graph)
        line_counter = 0
        myfile = '/'.join((self.rawdir, self.files[taxon]['file']))
        LOG.info("Processing Chr bands from FILE: %s", myfile)
        geno = Genotype(self.graph)
        monochrom = Monochrom(self.graph_type, self.are_bnodes_skized)

        # used to hold band definitions for a chr
        # in order to compute extent of encompasing bands

        mybands = {}
        # build the organism's genome from the taxon
        genome_label = self.files[taxon]['genome_label']
        taxon_id = 'NCBITaxon:' + taxon

        # add the taxon as a class.  adding the class label elsewhere
        model.addClassToGraph(taxon_id, None)
        model.addSynonym(taxon_id, genome_label)

        geno.addGenome(taxon_id, genome_label)

        # add the build and the taxon it's in
        build_num = self.files[taxon]['build_num']
        build_id = 'UCSC:' + build_num
        geno.addReferenceGenome(build_id, build_num, taxon_id)

        # process the bands
        col = ['scaffold', 'start', 'stop', 'band_num', 'rtype']
        with gzip.open(myfile, 'rb') as f:
            for line in f:
                line_counter += 1
                # skip comments
                line = line.decode().strip()
                if line[0] == '#' or line_counter > limit:
                    continue
                # chr13	4500000	10000000	p12	stalk
                row = line.split('\t')
                scaffold = row[col.index('scaffold')]
                start = row[col.index('start')]
                stop = row[col.index('stop')]
                band_num = row[col.index('band_num')].strip()
                rtype = row[col.index('rtype')]

                # NOTE some less-finished genomes have
                # placed and unplaced scaffolds
                # * Placed scaffolds:
                #       the scaffolds have been placed within a chromosome.
                # * Unlocalized scaffolds:
                #   although the chromosome within which the scaffold occurs
                #   is known, the scaffold's position or orientation
                #   is not known.
                # * Unplaced scaffolds:
                #   it is not known which chromosome the scaffold belongs to
                #
                # find out if the thing is a full on chromosome, or a scaffold:
                # ex: unlocalized scaffold: chr10_KL568008v1_random
                # ex: unplaced scaffold: chrUn_AABR07022428v1
                placed_scaffold_pattern = r'(chr(?:\d+|X|Y|Z|W|M))'
                unlocalized_scaffold_pattern = placed_scaffold_pattern+r'_(\w+)_random'
                unplaced_scaffold_pattern = r'chr(Un(?:_\w+)?)'

                mch = re.match(placed_scaffold_pattern + r'$', scaffold)
                if mch is not None and len(mch.groups()) == 1:
                    # the chromosome is the first match of the pattern
                    chrom_num = mch.group(1)
                else:
                    # skip over anything that isn't a placed_scaffold
                    # at the class level
                    LOG.info("Found non-placed chromosome %s", scaffold)
                    chrom_num = None

                m_chr_unloc = re.match(unlocalized_scaffold_pattern, scaffold)
                m_chr_unplaced = re.match(unplaced_scaffold_pattern, scaffold)

                scaffold_num = None
                if mch:
                    pass
                elif m_chr_unloc is not None and len(m_chr_unloc.groups()) == 2:
                    chrom_num = m_chr_unloc.group(1)
                    scaffold_num = chrom_num + '_' + m_chr_unloc.group(2)
                elif m_chr_unplaced is not None and len(m_chr_unplaced.groups()) == 1:
                    scaffold_num = m_chr_unplaced.group(1)
                else:
                    LOG.error(
                        "There's a chr pattern that we aren't matching: %s", scaffold)

                if chrom_num is not None:
                    # the chrom class (generic) id
                    chrom_class_id = makeChromID(chrom_num, taxon, 'CHR')

                    # first, add the chromosome class (in the taxon)
                    geno.addChromosomeClass(
                        chrom_num, taxon_id, self.files[taxon]['genome_label'])

                    # then, add the chromosome instance (from the given build)
                    geno.addChromosomeInstance(
                        chrom_num, build_id, build_num, chrom_class_id)

                    # add the chr to the hashmap of coordinates for this build
                    # the chromosome coordinate space is itself
                    if chrom_num not in mybands.keys():
                        mybands[chrom_num] = {
                            'min': 0,
                            'max': int(stop),
                            'chr': chrom_num,
                            'ref': build_id,
                            'parent': None,
                            'stain': None,
                            'type': self.globaltt['chromosome']}

                if scaffold_num is not None:
                    # this will put the coordinates of the scaffold
                    # in the scaffold-space and make sure that the scaffold
                    # is part of the correct parent.
                    # if chrom_num is None,
                    # then it will attach it to the genome,
                    # just like a reg chrom
                    mybands[scaffold_num] = {
                        'min': start,
                        'max': stop,
                        'chr': scaffold_num,
                        'ref': build_id,
                        'parent': chrom_num,
                        'stain': None,
                        'type': self.globaltt['assembly_component'],
                        'synonym': scaffold}

                parents = list()
                if band_num is not None and band_num != '':
                    # add the specific band
                    mybands[chrom_num+band_num] = {
                        'min': start,
                        'max': stop,
                        'chr': chrom_num,
                        'ref': build_id,
                        'parent': None,
                        'stain': None,
                        'type': None}

                    # add the staining intensity of the band
                    if re.match(r'g(neg|pos|var)', rtype):
                        mybands[chrom_num+band_num]['stain'] = self.resolve(rtype)

                    # get the parent bands, and make them unique
                    parents = list(
                        monochrom.make_parent_bands(band_num, set()))
                    # alphabetical sort will put them in smallest to biggest,
                    # so we reverse
                    parents.sort(reverse=True)
                    # print('parents of',chrom,band,':',parents)

                    if len(parents) > 0:
                        mybands[chrom_num + band_num]['parent'] = chrom_num + parents[0]

                # loop through the parents and add them to the hash
                # add the parents to the graph, in hierarchical order
                # TODO PYLINT Consider using enumerate
                # instead of iterating with range and len
                for i in range(len(parents)):
                    rti = getChrPartTypeByNotation(parents[i])

                    pnum = chrom_num+parents[i]
                    sta = int(start)
                    sto = int(stop)
                    if pnum not in mybands.keys():
                        # add the parental band to the hash
                        bnd = {
                            'min': min(sta, sto),
                            'max': max(sta, sto),
                            'chr': chrom_num,
                            'ref': build_id,
                            'parent': None,
                            'stain': None,
                            'type': rti}
                        mybands[pnum] = bnd
                    else:
                        # band already in the hash means it's a grouping band
                        # need to update the min/max coords
                        bnd = mybands.get(pnum)
                        bnd['min'] = min(sta, sto, bnd['min'])
                        bnd['max'] = max(sta, sto, bnd['max'])
                        mybands[pnum] = bnd

                        # also, set the max for the chrom
                        chrom = mybands.get(chrom_num)
                        chrom['max'] = max(sta, sto, chrom['max'])
                        mybands[chrom_num] = chrom

                    # add the parent relationships to each
                    if i < len(parents) - 1:
                        mybands[pnum]['parent'] = chrom_num+parents[i+1]
                    else:
                        # add the last one (p or q usually)
                        # as attached to the chromosome
                        mybands[pnum]['parent'] = chrom_num

        f.close()  # end looping through file

        # loop through the hash and add the bands to the graph
        for bnd in mybands.keys():
            myband = mybands.get(bnd)
            band_class_id = makeChromID(bnd, taxon, 'CHR')
            band_class_label = makeChromLabel(bnd, genome_label)
            band_build_id = makeChromID(bnd, build_num, 'MONARCH')
            band_build_label = makeChromLabel(bnd, build_num)
            # the build-specific chrom
            chrom_in_build_id = makeChromID(myband['chr'], build_num, 'MONARCH')
            # if it's != part, then add the class
            if myband['type'] != self.globaltt['assembly_component']:
                model.addClassToGraph(
                    band_class_id, band_class_label, myband['type'])
                bfeature = Feature(
                    self.graph, band_build_id, band_build_label, band_class_id)
            else:
                bfeature = Feature(
                    self.graph, band_build_id, band_build_label, myband['type'])
                if 'synonym' in myband:
                    model.addSynonym(band_build_id, myband['synonym'])

            if myband['parent'] is None:
                if myband['type'] == self.globaltt['assembly_component']:
                    # since we likely don't know the chr,
                    # add it as a part of the build
                    geno.addParts(band_build_id, build_id)
            elif myband['type'] == self.globaltt['assembly_component']:
                # geno.addParts(band_build_id, chrom_in_build_id)
                parent_chrom_in_build = makeChromID(
                    myband['parent'], build_num, 'MONARCH')
                bfeature.addSubsequenceOfFeature(parent_chrom_in_build)

            # add the band as a feature
            # (which also instantiates the owl:Individual)
            bfeature.addFeatureStartLocation(myband['min'], chrom_in_build_id)
            bfeature.addFeatureEndLocation(myband['max'], chrom_in_build_id)
            if 'stain' in myband and myband['stain'] is not None:
                bfeature.addFeatureProperty(
                    self.globaltt['has_sequence_attribute'], myband['stain'])

            # type the band as a faldo:Region directly (add_region=False)
            # bfeature.setNoBNodes(self.nobnodes)
            # to come when we merge in ZFIN.py
            bfeature.addFeatureToGraph(False)

        return
547269
def main():
    """"""
    import argparse
    prs = argparse.ArgumentParser(__doc__,
                                  formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    prs.add_argument('--taxon_id', type=str,
                     help='NCBI taxon ID, must match exact species/strain used by GO Central, e.g. 4896 for S Pombe')
    prs.add_argument('--golr_url', default='http://golr.geneontology.org/solr/', type=str,
                     help='NCBI taxon ID, must match exact species/strain used by GO Central, e.g. 4896 for S Pombe')
    prs.add_argument('-o', default=None, type=str,
                     help="Specifies the name of the output file")
    prs.add_argument('--max_rows', default=100000, type=int,
                     help="maximum rows to be fetched")

    args = prs.parse_args()

    solr = pysolr.Solr(args.golr_url, timeout=30)

    sys.stderr.write("TAX:"+args.taxon_id+"\n")
    results = solr.search(q='document_category:"bioentity" AND taxon:"NCBITaxon:'+args.taxon_id+'"',
                          fl='bioentity_label,annotation_class_list', rows=args.max_rows)
    sys.stderr.write("NUM GENES:"+str(len(results))+"\n")
    if (len(results) ==0):
        sys.stderr.write("NO RESULTS")
        exit(1)
    if (len(results) == args.max_rows):
        sys.stderr.write("max_rows set too low")
        exit(1)

    file_out = sys.stdout if args.o is None else open(args.o, 'w')
    for r in results:
        gene_symbol = r['bioentity_label']
        sys.stderr.write(gene_symbol+"\n")
        if 'annotation_class_list' in r:
            file_out.write(r['bioentity_label']+"\t" + ';'.join(r['annotation_class_list'])+"\n")
        else:
            sys.stderr.write("no annotations for "+gene_symbol+"\n")
            

    if args.o is not None:
        file_out.close()
        sys.stdout.write("  WROTE: {}\n".format(args.o))
1141671
def df_pdb_metadata(self):
        """"""
        if self.num_structures == 0:
            log.error('No experimental PDB structures have been mapped to protein')
            return pd.DataFrame()

        pdb_pre_df = []

        not_showing_info = []
        for p in self.get_experimental_structures():
            if not p.structure_file:
                not_showing_info.append(p.id)
                log.debug('{}: PDB file has not been downloaded, run "pdb_downloader_and_metadata" \
                    to download all structures'.format(p.id))
                continue

            infodict = p.get_dict(df_format=True)
            infodict['pdb_id'] = p.id
            pdb_pre_df.append(infodict)

        log.warning('Not showing info for mapped PDB entries, as they have not been downloaded yet. Run pdb_downloader_and_metadata')

        cols = ['pdb_id', 'pdb_title', 'description', 'experimental_method', 'mapped_chains',
                'resolution', 'chemicals', 'date', 'taxonomy_name',
                'structure_file']
        df = pd.DataFrame.from_records(pdb_pre_df, columns=cols).set_index('pdb_id')
        return ssbio.utils.clean_df(df)
393312
def from_genes(cls, genes: List[ExpGene]):
        """"""
        data = [g.to_dict() for g in genes]
        index = [d.pop('ensembl_id') for d in data]
        table = cls(data, index=index)
        return table
993406
def _get_entity_pair(self, entity_id):
        
        entity = self._entities.get(entity_id)
        try:
            input_entity = utils.get_input_peer(entity)
        except TypeError:
            try:
                input_entity = self._client._entity_cache[entity_id]
            except KeyError:
                input_entity = None

        return entity, input_entity
278055
def get_obsmeta(self, lcid):
        
        if self._obsdata is None:
            self._obsdata = fetch_rrlyrae_fitdata()
        i = np.where(self._obsdata['id'] == lcid)[0]
        if len(i) == 0:
            raise ValueError("invalid lcid: {0}".format(lcid))
        return self._obsdata[i[0]]
72623
def attributer(self):
        
        from Bio import SeqIO
        import operator
        for sample in self.runmetadata.samples:
            # Load the records from the target file into a dictionary
            record_dict = SeqIO.to_dict(SeqIO.parse(sample[self.analysistype].baitfile, "fasta"))
            sample[self.analysistype].classification = set()
            sample[self.analysistype].genera = dict()
            # Add all the genera with hits into the set of genera
            for result in sample[self.analysistype].results:
                genus, species = record_dict[result].description.split('|')[-1].split()[:2]
                sample[self.analysistype].classification.add(genus)
                sample[self.analysistype].genera[result] = genus
            # Convert the set to a list for easier JSON serialisation
            sample[self.analysistype].classification = list(sample[self.analysistype].classification)
            # If there is a mixed sample, then further analyses will be complicated
            if len(sample[self.analysistype].classification) > 1:
                # print('multiple: ', sample.name, sample[self.analysistype].classification)
                sample.general.closestrefseqgenus = sample[self.analysistype].classification
                # sample.general.bestassemblyfile = 'NA'
                sample[self.analysistype].multiple = True
            else:
                sample[self.analysistype].multiple = False

                try:
                    # Recreate the results dictionary with the percent identity as a float rather than a string
                    sample[self.analysistype].intresults = \
                        {key: float(value) for key, value in sample[self.analysistype].results.items()}
                    # Set the best hit to be the top entry from the sorted results
                    sample[self.analysistype].besthit = sorted(sample[self.analysistype].intresults.items(),
                                                               key=operator.itemgetter(1), reverse=True)[0]
                    sample.general.closestrefseqgenus = sample[self.analysistype].classification[0]
                except IndexError:
                    sample.general.bestassemblyfile = 'NA'
387164
def cli(ctx, organism="", sequence=""):
    
    return ctx.gi.annotations.get_features(organism=organism, sequence=sequence)
1075193
def get_strain_label(entry, viral=False):
    
    def get_strain(entry):
        strain = entry['infraspecific_name']
        if strain != '':
            strain = strain.split('=')[-1]
            return strain

        strain = entry['isolate']
        if strain != '':
            return strain

        if len(entry['organism_name'].split(' ')) > 2 and not viral:
            strain = ' '.join(entry['organism_name'].split(' ')[2:])
            return strain

        return entry['assembly_accession']

    def cleanup(strain):
        strain = strain.strip()
        strain = strain.replace(' ', '_')
        strain = strain.replace(';', '_')
        strain = strain.replace('/', '_')
        strain = strain.replace('\\', '_')
        return strain

    return cleanup(get_strain(entry))
395618
def get_ecf_props(ep_id, ep_id_ns, rsvc_id=None, ep_ts=None):
    
    results = {}
    if not ep_id:
        raise ArgumentError("ep_id", "ep_id must be a valid endpoint id")
    results[ECF_ENDPOINT_ID] = ep_id
    if not ep_id_ns:
        raise ArgumentError("ep_id_ns", "ep_id_ns must be a valid namespace")
    results[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = ep_id_ns
    if not rsvc_id:
        rsvc_id = get_next_rsid()
    results[ECF_RSVC_ID] = rsvc_id
    if not ep_ts:
        ep_ts = time_since_epoch()
    results[ECF_ENDPOINT_TIMESTAMP] = ep_ts
    return results
1121853
def download_kegg_gene_metadata(gene_id, outdir=None, force_rerun=False):
    
    if not outdir:
        outdir = ''

    # Replace colon with dash in the KEGG gene ID
    outfile = op.join(outdir, '{}.kegg'.format(custom_slugify(gene_id)))

    if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
        raw_text = bs_kegg.get("{}".format(gene_id))
        if raw_text == 404:
            return

        with io.open(outfile, mode='wt', encoding='utf-8') as f:
            f.write(raw_text)

        log.debug('{}: downloaded KEGG metadata file'.format(outfile))
    else:
        log.debug('{}: KEGG metadata file already exists'.format(outfile))

    return outfile
609500
def get_state_data(cls, entity):
        
        attrs = get_domain_class_attribute_iterator(type(entity))
        return dict([(attr,
                      get_nested_attribute(entity, attr.entity_attr))
                     for attr in attrs
                     if not attr.entity_attr is None])