What are the gene IDs associated with a given gene name?
        (due to copy events, there might be multiple genes per name)
176579
def gene_ids_of_gene_name(self, gene_name):
        
        results = self._query_gene_ids("gene_name", gene_name)
        if len(results) == 0:
            raise ValueError("Gene name not found: %s" % gene_name)
        return results
478993
def _get_identifiers(self, limit):
        

        LOG.info("getting identifier mapping")
        line_counter = 0
        f = '/'.join((self.rawdir, self.files['identifiers']['file']))
        myzip = ZipFile(f, 'r')
        # assume that the first entry is the item
        fname = myzip.namelist()[0]
        foundheader = False

        # TODO align this species filter with the one above
        # speciesfilters = 'Homo sapiens,Mus musculus,Drosophila melanogaster,
        # Danio rerio, Caenorhabditis elegans,Xenopus laevis'.split(',')

        speciesfilters = 'Homo sapiens,Mus musculus'.split(',')
        with myzip.open(fname, 'r') as csvfile:
            for line in csvfile:
                # skip header lines
                if not foundheader:
                    if re.match(r'BIOGRID_ID', line.decode()):
                        foundheader = True
                    continue

                line = line.decode().strip()
                # BIOGRID_ID
                # IDENTIFIER_VALUE
                # IDENTIFIER_TYPE
                # ORGANISM_OFFICIAL_NAME
                # 1	814566	ENTREZ_GENE	Arabidopsis thaliana
                (biogrid_num, id_num, id_type,
                 organism_label) = line.split('\t')

                if self.test_mode:
                    graph = self.testgraph
                    # skip any genes that don't match our test set
                    if int(biogrid_num) not in self.biogrid_ids:
                        continue
                else:
                    graph = self.graph

                model = Model(graph)

                # for each one of these,
                # create the node and add equivalent classes
                biogrid_id = 'BIOGRID:'+biogrid_num
                prefix = self.localtt[id_type]

                # TODO make these filters available as commandline options
                # geneidtypefilters='NCBIGene,OMIM,MGI,FlyBase,ZFIN,MGI,HGNC,
                #                   WormBase,XenBase,ENSEMBL,miRBase'.split(',')
                geneidtypefilters = 'NCBIGene,MGI,ENSEMBL,ZFIN,HGNC'.split(',')
                # proteinidtypefilters='HPRD,Swiss-Prot,NCBIProtein'
                if (speciesfilters is not None) \
                        and (organism_label.strip() in speciesfilters):
                    line_counter += 1
                    if (geneidtypefilters is not None) \
                            and (prefix in geneidtypefilters):
                        mapped_id = ':'.join((prefix, id_num))
                        model.addEquivalentClass(biogrid_id, mapped_id)
                    # this symbol will only get attached to the biogrid class
                    elif id_type == 'OFFICIAL_SYMBOL':
                        model.addClassToGraph(biogrid_id, id_num)
                    # elif (id_type == 'SYNONYM'):
                    #   FIXME - i am not sure these are synonyms, altids?
                    #   gu.addSynonym(g,biogrid_id,id_num)

                if not self.test_mode and limit is not None and line_counter > limit:
                    break

        myzip.close()

        return
689409
def get_gene(self, gene_name):
        
        if not gene_name:
            return

        gene_pk = self.genes.get(gene_name)
        if gene_pk:
            return gene_pk

        chrom = self.chromosomes[self.variants.chrom]
        gene = Gene.objects.find(gene_name, chrom, create=True)
        if gene:
            return gene.pk
157671
def get_gene_source_set(gtf):
    
    gene_to_source = {}
    db = get_gtf_db(gtf)
    for feature in complete_features(db):
        gene_id = feature['gene_id'][0]
        sources = gene_to_source.get(gene_id, set([])).union(set([feature.source]))
        gene_to_source[gene_id] = sources
    return gene_to_source
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
270999
def _add_genes(self, variant_obj):
        """"""
        genes = []
        ensembl_ids = []
        hgnc_symbols = []
        
        if variant_obj.transcripts:
            for transcript in variant_obj.transcripts:
                if transcript.ensembl_id:
                    ensembl_ids.append(transcript.ensembl_id)
                if transcript.hgnc_symbol:
                    hgnc_symbols.append(transcript.hgnc_symbol)

        else:
            hgnc_symbols = variant_obj.gene_symbols
        
        genes = get_gene_info(
                        ensembl_ids=ensembl_ids, 
                        hgnc_symbols=hgnc_symbols
                        )
            
        for gene in genes:
            variant_obj.add_gene(gene)
223849
def from_gene_ids(cls, gene_ids: List[str]):
        """"""
        genes = [ExpGene(id_) for id_ in gene_ids]
        return cls.from_genes(genes)
371118
static public void addGeneIDGFF2GeneFeatures(LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList, FeatureList listGenes) throws Exception {
		Collection<String> geneIds = listGenes.attributeValues("gene_id");
		for (String geneid : geneIds) {
			FeatureList gene = listGenes.selectByAttribute("gene_id", geneid);
			FeatureI geneFeature = gene.get(0);
			ChromosomeSequence seq = chromosomeSequenceList.get(geneFeature.seqname());
			geneid = geneid.replaceAll("_", ".G");
			AccessionID geneAccessionID = new AccessionID(geneid);
			GeneSequence geneSequence = null;
			Collection<String> transcriptids = gene.attributeValues("gene_id");
			for (String transcriptid : transcriptids) {
				// get all the individual features (exons, CDS regions, etc.) of this gene
				FeatureList transcriptFeature = listGenes.selectByAttribute("gene_id", transcriptid);
				transcriptid = transcriptid.replaceAll("_", ".G");




				//      String seqName = feature.seqname();
				//FeatureI startCodon = null;
				//FeatureI stopCodon = null;
				Integer startCodonBegin = null;
				Integer stopCodonEnd = null;
				//String startCodonName = "";
				//String stopCodonName = "";


				// now select only the coding regions of this gene
				FeatureList firstFeatures = transcriptFeature.selectByType("First");
				FeatureList terminalFeatures = transcriptFeature.selectByType("Terminal");
				FeatureList internalFeatures = transcriptFeature.selectByType("Internal");
				FeatureList singleFeatures = transcriptFeature.selectByType("Single");
				FeatureList cdsFeatures = new FeatureList();
				cdsFeatures.add(firstFeatures);
				cdsFeatures.add(terminalFeatures);
				cdsFeatures.add(internalFeatures);
				cdsFeatures.add(singleFeatures);
				// sort them
				cdsFeatures = cdsFeatures.sortByStart();
				Strand strand = Strand.POSITIVE;
				FeatureI feature = cdsFeatures.get(0);
				if (feature.location().isNegative()) {
					strand = Strand.NEGATIVE;
				}
				if (startCodonBegin == null) {
					FeatureI firstFeature = cdsFeatures.get(0);
					if (strand == Strand.NEGATIVE) {
						startCodonBegin = firstFeature.location().bioEnd();
					} else {
						startCodonBegin = firstFeature.location().bioStart();
					}
				}

				if (stopCodonEnd == null) {

					FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
					if (strand == Strand.NEGATIVE) {
						stopCodonEnd = lastFeature.location().bioStart();
					} else {
						stopCodonEnd = lastFeature.location().bioEnd();
					}
				}
				//for gtf ordering can be strand based so first is last and last is first
				if (startCodonBegin > stopCodonEnd) {
					int temp = startCodonBegin;
					startCodonBegin = stopCodonEnd;
					stopCodonEnd = temp;
				}

				AccessionID transcriptAccessionID = new AccessionID(transcriptid);
				if (geneSequence == null) {
					geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);
					geneSequence.setSource(((Feature) feature).source());
				} else {
					//if multiple transcripts for one gene make sure the gene is defined as the min and max start/end

					if (startCodonBegin < geneSequence.getBioBegin()) {
						geneSequence.setBioBegin(startCodonBegin);
					}
					if (stopCodonEnd > geneSequence.getBioBegin()) {
						geneSequence.setBioEnd(stopCodonEnd);
					}

				}
				TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);
				/*
				if (startCodon != null) {
					if (startCodonName == null || startCodonName.length() == 0) {
						startCodonName = transcriptid + "-start_codon-" + startCodon.location().bioStart() + "-" + startCodon.location().bioEnd();
					}
					transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());
				}
				if (stopCodon != null) {
					if (stopCodonName == null || stopCodonName.length() == 0) {
						stopCodonName = transcriptid + "-stop_codon-" + stopCodon.location().bioStart() + "-" + stopCodon.location().bioEnd();
					}
					transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());
				}
				*/

				for (FeatureI cdsFeature : cdsFeatures) {
					Feature cds = (Feature) cdsFeature;
					String cdsName = cds.getAttribute("transcript_name");
					if (cdsName == null || cdsName.length() == 0) {
						cdsName = transcriptid + "-cds-" + cds.location().bioStart() + "-" + cds.location().bioEnd();
					}
					AccessionID cdsAccessionID = new AccessionID(cdsName);
					//ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());
					CDSSequence cdsSequence = transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), cds.frame());
					cdsSequence.setSequenceScore(cds.score());
				}
			}
		}

	}
956567
def get_symbol_id_map(self):
        

        symbol_id_map = {}
        f = '/'.join((self.rawdir, self.files['genes']['file']))
        with open(f, 'r', encoding="utf8") as csvfile:
            filereader = csv.reader(csvfile, delimiter='\t', quotechar='\"')
            for row in filereader:
                (hgnc_id, symbol, name, locus_group, locus_type, status,
                 location, location_sortable, alias_symbol, alias_name,
                 prev_symbol, prev_name, gene_family, gene_family_id,
                 date_approved_reserved, date_symbol_changed,
                 date_name_changed, date_modified, entrez_id, ensembl_gene_id,
                 vega_id, ucsc_id, ena, refseq_accession, ccds_id, uniprot_ids,
                 pubmed_id, mgd_id, rgd_id, lsdb, cosmic, omim_id, mirbase,
                 homeodb, snornabase, bioparadigms_slc, orphanet,
                 pseudogene_org, horde_id, merops, imgt, iuphar,
                 kznf_gene_catalog, mamit_trnadb, cd, lncrnadb, enzyme_id,
                 intermediate_filament_db) = row

                symbol_id_map[symbol.strip()] = hgnc_id

        return symbol_id_map
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]
136325
def _splitGenoGeneWindow(self,annotation_file=None,cis=1e4,funct='protein_coding',minSnps=1.,maxSnps=SP.inf):
        
         #1. load annotation
        assert annotation_file is not None, 'Splitter:: specify annotation file'
        try:
            f = h5py.File(annotation_file,'r')
            geneID = f['geneID'][:]
            gene_chrom = f['chrom'][:]
            gene_start = f['start'][:]
            gene_end = f['end'][:]
            gene_strand = f['strand'][:]
            gene_function = f['function'][:]
            f.close()
        except:
            print('Splitter:: format annotation file not valid')

        # if funct is not None, it has to be a list
        if funct is not None and funct!=list:   funct=[funct]

        windows = []
        nSnps   = []
        Igene   = []
        #2. calculates windows 
        for gene_i in range(geneID.shape[0]):
            if funct is not None:
                if gene_function[gene_i] not in funct:
                    Igene.append(False)
                    continue
            wnd = [gene_chrom[gene_i],gene_start[gene_i]-cis,gene_end[gene_i]+cis]
            Ir = (self.chrom==wnd[0])*(self.pos>=wnd[1])*(self.pos<=wnd[2])
            _nSnps = Ir.sum()
            if _nSnps>=minSnps and _nSnps<=maxSnps:
                windows.append(wnd)
                nSnps.append(_nSnps)
                Igene.append(True)
            else:
                Igene.append(False)
        Igene = SP.array(Igene)
        self.info['nSnps'] = SP.array(nSnps)
        self.info['geneID']        = geneID[Igene]
        self.info['gene_start']    = gene_start[Igene]
        self.info['gene_end']      = gene_end[Igene]
        self.info['gene_strand']   = gene_strand[Igene]
        self.info['gene_function'] = gene_function[Igene]
        return SP.array(windows)
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
1129459
def _add_vertex_attributes_by_genes(self, genes: List[Gene]) -> None:
        
        for gene in genes:
            try:
                vertex = self.graph.vs.find(name=str(gene.entrez_id)).index
                self.graph.vs[vertex]['l2fc'] = gene.log2_fold_change
                self.graph.vs[vertex]['symbol'] = gene.symbol
                self.graph.vs[vertex]['padj'] = gene.padj
            except ValueError:
                pass
950081
def get_gene_id(gene_name):
    '''

    '''
    from intermine.webservice import Service

    service = Service('http://yeastmine.yeastgenome.org/yeastmine/service')

    # Get a new query on the class (table) you will be querying:
    query = service.new_query('Gene')

    # The view specifies the output columns
    query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol',
                   'name', 'sgdAlias', 'crossReferences.identifier',
                   'crossReferences.source.name')

    # Uncomment and edit the line below (the default) to select a custom sort
    # order:
    # query.add_sort_order('Gene.primaryIdentifier', 'ASC')

    # You can edit the constraint values below
    query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B')
    query.add_constraint('Gene', 'LOOKUP', gene_name, code='A')

    # Uncomment and edit the code below to specify your own custom logic:
    # query.set_logic('A and B')

    for row in query.rows():
        gid = row['secondaryIdentifier']
    return gid
117530
def features(self, other_start, other_end):
        
        # completely encases gene.
        if other_start <= self.start and other_end >= self.end:
            return ['gene' if self.cdsStart != self.cdsEnd else 'nc_gene']
        other = Interval(other_start, other_end)
        ovls = []
        tx = 'txEnd' if self.strand == "-" else 'txStart'
        if hasattr(self, tx) and other_start <= getattr(self, tx) <= other_end \
            and self.cdsStart != self.cdsEnd:
                ovls = ["TSS"]
        for ftype in ('introns', 'exons', 'utr5', 'utr3', 'cdss'):
            feats = getattr(self, ftype)
            if not isinstance(feats, list): feats = [feats]
            if any(Interval(f[0], f[1]).overlaps(other) for f in feats):
                ovls.append(ftype[:-1] if ftype[-1] == 's' else ftype)
        if 'cds' in ovls:
            ovls = [ft for ft in ovls if ft != 'exon']
        if self.cdsStart == self.cdsEnd:
            ovls = ['nc_' + ft for ft in ovls]
        return ovls
684424
def get_gene_ids(fusion_bed):
    
    with open(fusion_bed, 'r') as f:
        gene_to_id = {}
        regex = re.compile(r'(?P<gene>ENSG\d*)')
        for line in f:
            line = line.split('\t')
            transcript, gene_bit, name = line[3].split(';')
            m = regex.search(gene_bit)
            if m:
                gene_to_id[name] = m.group('gene')
    return gene_to_id
763976
def random_variants(
        count,
        genome_name="GRCh38",
        deletions=True,
        insertions=True,
        random_seed=None):
    
    rng = random.Random(random_seed)
    ensembl = genome_for_reference_name(genome_name)

    if ensembl in _transcript_ids_cache:
        transcript_ids = _transcript_ids_cache[ensembl]
    else:
        transcript_ids = ensembl.transcript_ids()
        _transcript_ids_cache[ensembl] = transcript_ids

    variants = []

    # we should finish way before this loop is over but just in case
    # something is wrong with PyEnsembl we want to avoid an infinite loop
    for _ in range(count * 100):
        if len(variants) < count:
            transcript_id = rng.choice(transcript_ids)
            transcript = ensembl.transcript_by_id(transcript_id)

            if not transcript.complete:
                continue

            exon = rng.choice(transcript.exons)
            base1_genomic_position = rng.randint(exon.start, exon.end)
            transcript_offset = transcript.spliced_offset(base1_genomic_position)
            seq = transcript.sequence

            ref = str(seq[transcript_offset])
            if transcript.on_backward_strand:
                ref = reverse_complement(ref)

            alt_nucleotides = [x for x in STANDARD_NUCLEOTIDES if x != ref]

            if insertions:
                nucleotide_pairs = [
                    x + y
                    for x in STANDARD_NUCLEOTIDES
                    for y in STANDARD_NUCLEOTIDES
                ]
                alt_nucleotides.extend(nucleotide_pairs)
            if deletions:
                alt_nucleotides.append("")
            alt = rng.choice(alt_nucleotides)
            variant = Variant(
                transcript.contig,
                base1_genomic_position,
                ref=ref,
                alt=alt,
                ensembl=ensembl)
            variants.append(variant)
        else:
            return VariantCollection(variants)
    raise ValueError(
        ("Unable to generate %d random variants, "
         "there may be a problem with PyEnsembl") % count)