DictList: All genes that have at least one experimental structure.
964614
def genes_with_experimental_structures(self):
        """"""
        return DictList(x for x in self.genes_with_structures if x.protein.num_structures_experimental > 0)
750108
def gene_features(self):
        
        nm, strand = self.gene_name, self.strand
        feats = [(self.chrom, self.start, self.end, nm, strand, 'gene')]
        for feat in ('introns', 'exons', 'utr5', 'utr3', 'cdss'):
            fname = feat[:-1] if feat[-1] == 's' else feat
            res = getattr(self, feat)
            if res is None or all(r is None for r in res): continue
            if not isinstance(res, list): res = [res]
            feats.extend((self.chrom, s, e, nm, strand, fname) for s, e in res)

        tss = self.tss(down=1)
        if tss is not None:
            feats.append((self.chrom, tss[0], tss[1], nm, strand, 'tss'))
            prom = self.promoter()
            feats.append((self.chrom, prom[0], prom[1], nm, strand, 'promoter'))

        return sorted(feats, key=itemgetter(1))
1167857
def get_other_gene_names(cls, entry):
        
        alternative_gene_names = []

        for alternative_gene_name in entry.iterfind("./gene/name"):

            if alternative_gene_name.attrib['type'] != 'primary':

                alternative_gene_name_dict = {
                    'type_': alternative_gene_name.attrib['type'],
                    'name': alternative_gene_name.text
                }

                alternative_gene_names.append(models.OtherGeneName(**alternative_gene_name_dict))

        return alternative_gene_names
1203080
def corewriter(self):
        
        printtime('Creating core allele files', self.start)
        for gene in sorted(self.genesequence):
            self.geneset.add(gene)
            # Set the name of the allele file
            genefile = os.path.join(self.coregenelocation, '{}.fasta'.format(gene))
            # If the file doesn't exist, create it
            if not os.path.isfile(genefile):
                with open(genefile, 'w') as core:
                    for count, sequence in enumerate(self.genesequence[gene]):
                        # The definition line is the gene name, and the allele number (count (+ 1 to compensate for
                        # base zero))
                        definitionline = '{}-{}'.format(gene, count + 1)
                        # Create a sequence record using BioPython
                        fasta = SeqRecord(Seq(sequence),
                                          # Without this, the header will be improperly formatted
                                          description='',
                                          # Use >:definitionline as the header
                                          id=definitionline)
                        # Use the SeqIO module to properly format the new sequence record
                        SeqIO.write(fasta, core, 'fasta')
                        for strain in self.coresequence[sequence]:
                            # Record the strain name, the gene name, and the allele number.
                            # [:-6] removes the contig number: 2014-SEQ-0276_00001 becomes 2014-SEQ-0276
                            try:
                                self.corealleles[strain[:-6]].update({gene: count + 1})
                            except KeyError:
                                self.corealleles[strain[:-6]] = {gene: count + 1}
            else:
                # If the file exists, don't recreate it; only iterate through the dictionary of gene sequences
                for count, sequence in enumerate(self.genesequence[gene]):
                    for strain in self.coresequence[sequence]:
                        # Populate the dictionary as above
                        try:
                            self.corealleles[strain[:-6]].update({gene: count + 1})
                        except KeyError:
                            self.corealleles[strain[:-6]] = {gene: count + 1}
        # Create a combined file of all the core genes to be used in typing strain(s) of interest
        if not os.path.isfile(os.path.join(self.coregenelocation, 'core_combined.fasta')):
            fastafiles = glob(os.path.join(self.coregenelocation, '*.fasta'))
            # Run the method for each allele
            self.combinealleles(fastafiles)
        # Run the profiler
        self.profiler()
938844
def get_pdbs_for_gene(bigg_model, bigg_gene, cache_dir=tempfile.gettempdir(), force_rerun=False):
    
    my_structures = []

    # Download gene info
    gene = ssbio.utils.request_json(link='http://bigg.ucsd.edu/api/v2/models/{}/genes/{}'.format(bigg_model, bigg_gene),
                                    outfile='{}_{}.json'.format(bigg_model, bigg_gene),
                                    outdir=cache_dir,
                                    force_rerun_flag=force_rerun)

    uniprots = []
    if 'database_links' in gene:
        if 'UniProt' in gene['database_links']:
            uniprots = [x['id'] for x in gene['database_links']['UniProt']]
        elif 'NCBI GI' in gene['database_links']:
            uniprots = []
            gis = [x['id'] for x in gene['database_links']['NCBI GI']]
            gi_uniprots = bs_unip.mapping(fr='P_GI', to='ACC', query=gis).values()
            uniprots.extend(gi_uniprots)
            uniprots = ssbio.utils.flatlist_dropdup(uniprots)
            uniprots = [x for x in uniprots if ssbio.databases.uniprot.is_valid_uniprot_id(x)]

    if uniprots:
        for u in uniprots:
            get_best_structure = ssbio.databases.pdb.best_structures(uniprot_id=u, outdir=cache_dir)
            if get_best_structure:
                for best_structure in get_best_structure:
                    my_structures.append((best_structure['pdb_id'], best_structure['chain_id']))

    return my_structures
669109
def group_reads_by_allele(allele_reads):
    
    allele_to_reads_dict = defaultdict(list)
    for allele_read in allele_reads:
        allele_to_reads_dict[allele_read.allele].append(allele_read)
    return allele_to_reads_dict
782965
def genes(self):
        """"""
        return [ExpGene.from_series(g)
                for i, g in self.reset_index().iterrows()]
1152135
def genes_with_a_representative_sequence(self):
        """"""
        return DictList(x for x in self.genes if x.protein.representative_sequence)
142000
def profiler(self):
        """"""
        # Initialise variables
        profiledata = defaultdict(make_dict)
        profileset = set()
        # supplementalset = ''
        genedict = {}
        # Find all the unique profiles to use with a set
        for sample in self.metadata:
            if sample[self.analysistype].profile != 'NA':
                profileset.add(sample[self.analysistype].profile[0])
                # if self.analysistype == 'rmlst':
                #     supplementalset = sample[self.analysistype].supplementalprofile
        # Extract the profiles for each set
        for sequenceprofile in profileset:
            # Clear the list of genes
            genelist = []
            for sample in self.metadata:
                if sequenceprofile == sample[self.analysistype].profile[0]:
                    # genelist = [os.path.split(x)[1].split('.')[0] for x in sample[self.analysistype].alleles]
                    genelist = sample[self.analysistype].allelenames
            try:
                # Open the sequence profile file as a dictionary
                profile = DictReader(open(sequenceprofile), dialect='excel-tab')
            # Revert to standard comma separated values
            except KeyError:
                # Open the sequence profile file as a dictionary
                profile = DictReader(open(sequenceprofile))
            # Iterate through the rows
            for row in profile:
                # Iterate through the genes
                for gene in genelist:
                    # Add the sequence profile, and type, the gene name and the allele number to the dictionary
                    try:
                        profiledata[sequenceprofile][row['ST']][gene] = row[gene]
                    except KeyError:
                        try:
                            profiledata[sequenceprofile][row['rST']][gene] = row[gene]
                        except KeyError:
                            raise

            # # Load the supplemental profile definitions
            # if self.analysistype == 'rmlst':
            #     supplementalprofile = DictReader(open(supplementalset), dialect='excel-tab')
            #     # Do the same with the supplemental profile
            #     for row in supplementalprofile:
            #         # Iterate through the genes
            #         for gene in genelist:
            #             # Add the sequence profile, and type, the gene name and the allele number to the dictionary
            #             profiledata[sequenceprofile][row['rST']][gene] = row[gene]
            # Add the gene list to a dictionary
            genedict[sequenceprofile] = sorted(genelist)
            # Add the profile data, and gene list to each sample
            for sample in self.metadata:
                if sample.general.bestassemblyfile != 'NA':
                    if sequenceprofile == sample[self.analysistype].profile[0]:
                        # Populate the metadata with the profile data
                        sample[self.analysistype].profiledata = profiledata[sample[self.analysistype].profile[0]]
                        # Add the allele directory to a list of directories used in this analysis
                        self.allelefolders.add(sample[self.analysistype].alleledir)
                        dotter()
402292
def gene_one_per_line(in_file, data):
    
    if in_file:
        # Report all duplicated annotations one-per-line
        one_per_line_file = "%s-opl.bed" % utils.splitext_plus(in_file)[0]
        if not utils.file_uptodate(one_per_line_file, in_file):
            with file_transaction(data, one_per_line_file) as tx_out_file:
                with open(tx_out_file, 'w') as out:
                    for r in pybedtools.BedTool(in_file):
                        for g in r.name.split(','):
                            out.write('\t'.join(map(str, [r.chrom, r.start, r.end, g])) + '\n')
        return one_per_line_file
1179580
def protein_statistics(self):
        """"""

        # TODO: can i use get_dict here instead
        d = {}

        d['id'] = self.id
        d['sequences'] = [x.id for x in self.sequences]
        d['num_sequences'] = self.num_sequences
        if self.representative_sequence:
            d['representative_sequence'] = self.representative_sequence.id
            d['repseq_gene_name'] = self.representative_sequence.gene_name
            d['repseq_uniprot'] = self.representative_sequence.uniprot
            d['repseq_description'] = self.representative_sequence.description
        d['num_structures'] = self.num_structures
        d['experimental_structures'] = [x.id for x in self.get_experimental_structures()]
        d['num_experimental_structures'] = self.num_structures_experimental
        d['homology_models'] = [x.id for x in self.get_homology_models()]
        d['num_homology_models'] = self.num_structures_homology
        if self.representative_structure:
            d['representative_structure'] = self.representative_structure.id
            d['representative_chain'] = self.representative_chain
            d['representative_chain_seq_coverage'] = self.representative_chain_seq_coverage
            d['repstruct_description'] = self.description
            if self.representative_structure.is_experimental:
                d['repstruct_resolution'] = self.representative_structure.resolution
        d['num_sequence_alignments'] = len(self.sequence_alignments)
        d['num_structure_alignments'] = len(self.structure_alignments)

        return d
685860
def listDatawraps() :
	""""""
	l = {"Genomes" : [], "SNPs" : []}
	for f in os.listdir(os.path.join(this_dir, "bootstrap_data/genomes")) :
		if f.find(".tar.gz") > -1 :
			l["Genomes"].append(f)
	
	for f in os.listdir(os.path.join(this_dir, "bootstrap_data/SNPs")) :
		if f.find(".tar.gz") > -1 :
			l["SNPs"].append(f)

	return l
149479
def standardize_genes(self, inplace=False):
        """"""
        matrix = self.center_genes(inplace=inplace)
        matrix.X[:,:] = matrix.X / \
            np.tile(np.std(matrix.X, axis=1, ddof=1), (matrix.n, 1)).T
        return matrix
237996
def get_experimental_structures(self):
        """"""
        # TODO: change to a property?
        if self.representative_structure:
            return DictList(x for x in self.structures if x.is_experimental and x.id != self.representative_structure.id)
        else:
            return DictList(x for x in self.structures if x.is_experimental)
1047823
def get_linc_rna_genes(
        path_or_buffer,
        remove_duplicates=True,
        **kwargs):
    

    """
    valid_biotypes = set(['lincRNA'])
    
    df = get_genes(path_or_buffer, valid_biotypes,
                   remove_duplicates=remove_duplicates, **kwargs)
    return df
1020817
def genes(self):
        
        if self._genes is None:
            self._genes = self.ensembl.genes_at_locus(
                self.contig, self.start, self.end)
        return self._genes
1073959
def df_pdb_ranking(self):
        """"""
        df = pd.DataFrame()
        for g in self.genes_with_experimental_structures:
            protein_df = g.protein.df_pdb_ranking.copy().reset_index()
            if not protein_df.empty:
                protein_df['gene'] = g.id
                df = df.append(protein_df)
        if df.empty:
            log.warning('Empty dataframe')
            return df
        else:
            return ssbio.utils.clean_df(df.set_index('gene'))