Find a gene based on the symbol or disambiguate using synonyms.
        If no gene is found, if the create is True, a new instance will be
        created with that symbol.
3371
def find(self, symbol, chrom=None, create=False):
        
        queryset = self.get_query_set()

        # Filter by chromosome if one is specified
        if chrom:
            queryset = queryset.filter(chr=chrom)

        # Look for direct match
        matches = queryset.filter(symbol__iexact=symbol)

        try:
            return matches[0]
        except IndexError:
            pass

        # Attempt to disambiguate, only if this is the only synonym may it be
        # associated
        potential = list(
            queryset.filter(synonyms__label__iexact=symbol).distinct())

        if len(potential) == 1:
            return potential[0]

        # Only if there are no matches should we create a new record,
        # otherwise the synonym war will continue
        if create and len(potential) == 0:
            instance = self.model(chr=chrom, symbol=symbol)
            try:
                instance.save()
            except IntegrityError:
                instance = queryset.get(chr=chrom, symbol=symbol)
            return instance
1031391
def _read(
    filename,
    schema,
    seq_label='sequence',
    alphabet=None,
    use_uids=True,
    **kwargs):
    
    # Check Alphabet if given
    if alphabet is None:
        alphabet = Bio.Alphabet.Alphabet()

    elif alphabet in ['dna', 'rna', 'protein', 'nucleotide']:
        alphabet = getattr(Bio.Alphabet, 'generic_{}'.format(alphabet))

    else:
        raise Exception(
            "The alphabet is not recognized. Must be 'dna', 'rna', "
            "'nucleotide', or 'protein'.")

    kwargs.update(alphabet=alphabet)

    # Prepare DataFrame fields.
    data = {
        'id': [],
        seq_label: [],
        'description': [],
        'label': []
    }
    if use_uids:
        data['uid'] = []

    # Parse Fasta file.
    for i, s in enumerate(SeqIO.parse(filename, format=schema, **kwargs)):
        data['id'].append(s.id)
        data[seq_label].append(str(s.seq))
        data['description'].append(s.description)
        data['label'].append(s.name)

        if use_uids:
            data['uid'].append(get_random_id(10))

    # Port to DataFrame.
    return pd.DataFrame(data)
1177193
def _init_nt(self, flds):
        """"""
        term = flds[1]
        genes_str = flds[5]
        # pylint: disable=bad-whitespace
        return self.ntobj(
            Category   =       flds[0],
            GO         =       term[:10], #  1  GO:0045202~synapse
            name       =       term[10:], #  1  GO:0045202~synapse
            Count      =   int(flds[2]),  #  2  94
            Perc       = float(flds[3]),  #  3  9.456740442655935
            PValue     = float(flds[4]),  #  4  6.102654380458156E-20
            Genes      =      genes_str, # 5 ['ENSMUSG00000052613', ...]
            Genes_set  = self.get_genes(genes_str), # 5 ['ENSMUSG00000052613', ...]
            List_Total =   int(flds[6]),  #  6  920
            Pop_Hits   =   int(flds[7]),  #  7  444
            Pop_Total  =   int(flds[8]),  #  8  12002
            Fold_Enrichment = float(flds[9]), # 9 2.7619173521347435
            Bonferroni = float(flds[10]), # 10  3.3930758355347344E-17
            Benjamini  = float(flds[11]), # 11  3.3930758355347344E-17
            FDR        = float(flds[12]))
1067776
def nr_genes(self):
        """"""
        if self['genes']:
            nr_genes = len(self['genes'])
        else:
            nr_genes = len(self['gene_symbols'])
        return nr_genes
1180194
def get_gene2aart(gene2section2gos, sec2chr):
        """"""
        geneid2str = {}
        for geneid, section2gos_gene in gene2section2gos.items():
            letters = [abc if s in section2gos_gene else "." for s, abc in sec2chr.items()]
            geneid2str[geneid] = "".join(letters)
        return geneid2str
809486
def _get_genes(self, variant):
        
        transcripts = variant['transcripts']
        ensembl_ids = [transcript['ensembl_id'] for transcript in
                       transcripts if transcript['ensembl_id']]
        hgnc_symbols = [transcript['hgnc_symbol'] for transcript in
                        transcripts if transcript['hgnc_symbol']]
        genes = get_gene_info(ensembl_ids, hgnc_symbols)
        return genes
1004250
def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:
        
        multiplexes = tuple(multiplex for multiplex in multiplexes if gene in multiplex.genes)
        for transition in self.transitions:
            if transition.gene == gene and set(transition.multiplexes) == set(multiplexes):
                return transition
        raise AttributeError(f'transition K_{gene.name}' + ''.join(f"+{multiplex!r}" for multiplex in multiplexes) + ' does not exist')
405982
def check_genes(self):
        
        gene_dna_set = set([g.dna for g in self.genes])
        assert gene_dna_set == self.dna_choices_set
605932
def get_gene_leaves(graph) -> Iterable[BaseEntity]:
    
    for node in get_nodes_by_function(graph, GENE):
        if graph.in_degree(node) != 0:
            continue

        if graph.out_degree(node) != 1:
            continue

        _, _, d = list(graph.out_edges(node, data=True))[0]

        if d[RELATION] == TRANSCRIBED_TO:
            yield node
156226
def get_goa_gene_sets(go_annotations):
    
    go_term_genes = OrderedDict()
    term_ids = {}
    for ann in go_annotations:
        term_ids[ann.go_term.id] = ann.go_term
        try:
            go_term_genes[ann.go_term.id].append(ann.db_symbol)
        except KeyError:
            go_term_genes[ann.go_term.id] = [ann.db_symbol]
    
    go_term_genes = OrderedDict(sorted(go_term_genes.items()))
    gene_sets = []
    for tid, genes in go_term_genes.items():
        go_term = term_ids[tid]
        gs = GeneSet(id=tid, name=go_term.name, genes=genes,
                     source='GO',
                     collection=go_term.domain_short,
                     description=go_term.definition)
        gene_sets.append(gs)
    gene_sets = GeneSetCollection(gene_sets)
    return gene_sets
542377
def _findAll(self, name, attrs, text, limit, generator, **kwargs):
        ""

        if isinstance(name, SoupStrainer):
            strainer = name
        # (Possibly) special case some findAll*(...) searches
        elif text is None and not limit and not attrs and not kwargs:
            # findAll*(True)
            if name is True:
                return [element for element in generator()
                        if isinstance(element, Tag)]
            # findAll*('tag-name')
            elif isinstance(name, basestring):
                return [element for element in generator()
                        if isinstance(element, Tag) and
                        element.name == name]
            else:
                strainer = SoupStrainer(name, attrs, text, **kwargs)
        # Build a SoupStrainer
        else:
            strainer = SoupStrainer(name, attrs, text, **kwargs)
        results = ResultSet(strainer)
        g = generator()
        while True:
            try:
                i = g.next()
            except StopIteration:
                break
            if i:
                found = strainer.search(i)
                if found:
                    results.append(found)
                    if limit and len(results) >= limit:
                        break
        return results
685830
def delete_gene(self, *gene_ids):
        """"""
        self.gene_ids = [gene_id for gene_id in self.gene_ids
                         if gene_id not in gene_ids]
1336905
def parse_from_args(synonyms):
    '''
    
    '''

    syns_str = ''.join(synonyms)

    syns_str = syns_str.replace(' ', '')
    
    syn_set = SynonymSet()

    # to check if we are parsing inside the parenthesis
    inside_set = False
    current_syn = ''
    current_syn_set = set()

    for char in syns_str:
        if char == '{':
            inside_set = True
            current_syn_set = set()
            continue

        if char == '}':
            inside_set = False
            current_syn_set.add(current_syn)

            syn_set.add_set(current_syn_set)

            current_syn = ''

            continue

        if not inside_set:
            raise Exception("Incorrect synonyms {}".format(syns_str))

        if char == ',':
            if current_syn == '':
                raise Exception("Incorrect synonyms {}".format(syns_str))

            current_syn_set.add(current_syn)
            current_syn = ''

            continue

        current_syn += char

    return syn_set
1317921
def genes_with_structures(self):
        """"""
        return DictList(x for x in self.genes if x.protein.num_structures > 0)
1074166
def make_degenerate_regex( motif_seq, molecule='dna' ):
	
	
	if not isinstance( motif_seq, six.string_types ):
		raise TypeError( "motif_seq must be a string!" )
		
	if molecule == 'dna':
		degenerate_code = { "A":"A", "B":"[CGT]", "C":"C", "D":"[AGT]", "G":"G", "H":"[ACT]", "K":"[GT]", "M":"[AC]", "N":"[ACGT]", "R":"[AG]", "S":"[GC]", "T":"T", "V":"[ACG]", "W":"[AT]", "Y":"[CT]" }
	elif molecule == 'rna':
		degenerate_code = { "A":"A", "B":"[CGU]", "C":"C", "D":"[AGU]", "G":"G", "H":"[ACU]", "K":"[GU]", "M":"[AC]", "N":"[ACGU]", "R":"[AG]", "S":"[GC]", "U":"U", "V":"[ACG]", "W":"[AU]", "Y":"[CU]" }
	else:
		raise ValueError( "make_degenerate_regex requires molecule to be dna or rna" )
	
	regex_string = ''
	
	idx = 0
	
	while idx < len( motif_seq ):
		curr = motif_seq[idx]
		
		count = 1
		
		for next_idx in range( idx+1, len( motif_seq ) ):
			next = motif_seq[next_idx]
			
			if next == curr:
				count += 1
			else:
				break
		
		regex_string += degenerate_code[curr]
		
		if count > 1:
			idx = idx + count - 1
			regex_string += "{%s}" % ( count )
		
		idx += 1
	
	return regex_string
1268515
def match_concept(self,string):
        ''''''
        matches = self.match_all_concepts(string)
        if len(matches)>0:
            return matches[0]
        return None
1026404
def _find_gene_list_from_bed(bed_file, base_file, data):
    
    # Check for a gene list, we can just return that.
    if is_gene_list(bed_file):
        return bed_file
    out_file = "%s-genes.txt" % utils.splitext_plus(base_file)[0]
    if not os.path.exists(out_file):
        genes = set([])
        import pybedtools
        with utils.open_gzipsafe(bed_file) as in_handle:
            for r in pybedtools.BedTool(in_handle):
                if r.name:
                    if not r.name.startswith("{"):
                        genes.add(r.name)
        with file_transaction(data, out_file) as tx_out_file:
            with open(tx_out_file, "w") as out_handle:
                if len(genes) > 0:
                    out_handle.write("\n".join(sorted(list(genes))) + "\n")
    if utils.file_exists(out_file):
        return out_file