get a dictionary of the set of all sources of the gene for a given
    transcript
494180
def get_transcript_source_set(gtf):
    
    gene_to_source = get_gene_source_set(gtf)
    transcript_to_source = {}
    db = get_gtf_db(gtf)
    for feature in complete_features(db):
        gene_id = feature['gene_id'][0]
        transcript_to_source[feature['transcript_id'][0]] = gene_to_source[gene_id]
    return transcript_to_source
810555
def _build_collapse_to_gene_dict(graph) -> Dict[BaseEntity, Set[BaseEntity]]:
    
    collapse_dict = defaultdict(set)
    r2g = {}

    for gene_node, rna_node, d in graph.edges(data=True):
        if d[RELATION] != TRANSCRIBED_TO:
            continue

        collapse_dict[gene_node].add(rna_node)
        r2g[rna_node] = gene_node

    for rna_node, protein_node, d in graph.edges(data=True):
        if d[RELATION] != TRANSLATED_TO:
            continue

        if rna_node not in r2g:
            raise ValueError('Should complete origin before running this function')

        collapse_dict[r2g[rna_node]].add(protein_node)

    return collapse_dict
297859
def get_gpd_line(self,transcript_name=None,gene_name=None,direction=None):
    """"""
    return transcript_to_gpd_line(self,transcript_name=transcript_name,gene_name=gene_name,direction=direction)
241856
def _get_snpeff_transcript(self, transcript_info):
        
        transcript = Transcript(
                hgnc_symbol = transcript_info.get('Gene_Name'),
                transcript_id = transcript_info.get('Feature'),
                ensembl_id = transcript_info.get('Gene_ID'),
                biotype = transcript_info.get('Transcript_BioType'),
                consequence = transcript_info.get('Annotation'),
                exon = transcript_info.get('Rank'),
                HGVSc = transcript_info.get('HGVS.c'),
                HGVSp = transcript_info.get('HGVS.p')
            )
        return transcript
378567
def get_rRNA(gtf):
    
    rRNA_biotypes = ["rRNA", "Mt_rRNA", "tRNA", "MT_tRNA"]
    features = set()
    with open_gzipsafe(gtf) as in_handle:
        for line in in_handle:
            if not "gene_id" in line or not "transcript_id" in line:
                continue
            if any(x in line for x in rRNA_biotypes):
                geneid = line.split("gene_id")[1].split(" ")[1]
                geneid = _strip_non_alphanumeric(geneid)
                geneid = _strip_feature_version(geneid)
                txid = line.split("transcript_id")[1].split(" ")[1]
                txid = _strip_non_alphanumeric(txid)
                txid = _strip_feature_version(txid)
                features.add((geneid, txid))
    return features
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
1036408
def get_target_transcript(self,min_intron=1):
    
    if min_intron < 1: 
      sys.stderr.write("ERROR minimum intron should be 1 base or longer\n")
      sys.exit()
    #tx = Transcript()
    rngs = [self.alignment_ranges[0][0].copy()]
    #rngs[0].set_direction(None)
    for i in range(len(self.alignment_ranges)-1):
      dist = self.alignment_ranges[i+1][0].start - rngs[-1].end-1
      #print 'dist '+str(dist)
      if dist >= min_intron:
        rngs.append(self.alignment_ranges[i+1][0].copy())
        #rngs[-1].set_direction(None)
      else:
        rngs[-1].end = self.alignment_ranges[i+1][0].end
    tx = Transcript(rngs,options=Transcript.Options(
         direction=self.strand,
         name = self.alignment_ranges[0][1].chr,
         gene_name = self.alignment_ranges[0][1].chr
                                                  ))
    #tx.set_exons_and_junctions_from_ranges(rngs)
    #tx.set_range()
    #tx.set_strand(self.get_strand())
    #tx.set_transcript_name(self.get_alignment_ranges()[0][1].chr)
    #tx.set_gene_name(self.get_alignment_ranges()[0][1].chr)
    return tx
330209
def _parse_gene_coordinates(file):
        
        id_map = {}
        col = ['gene_curie', 'start', 'end', 'strand', 'build']
        if os.path.exists(os.path.join(os.path.dirname(__file__), file)):
            with open(os.path.join(os.path.dirname(__file__), file)) as tsvfile:
                reader = csv.reader(tsvfile, delimiter="\t")
                for row in reader:
                    id_map[row[col.index('gene_curie')]] = {
                        'start': row[col.index('start')],
                        'end': row[col.index('end')],
                        'strand': row[col.index('strand')],
                        'build': row[col.index('build')]
                    }
        return id_map
716984
def _rngs(self):
      """"""
      outputs = []
      if len(self._exon_groups)==1:
         return [self._exon_groups.consensus('single')]
      z = 0 #output count
      begin = 0
      meeting_criteria = [i for i in range(0,len(self._exon_groups)) if  len(self._exon_groups) >= self._evidence]
      if len(meeting_criteria) == 0: return []
      finish = len(meeting_criteria)
      if len(meeting_criteria) > 0:
         begin = meeting_criteria[0]
         finish = meeting_criteria[-1]
      for i in range(0,len(self._exon_groups)):
         if z == begin:
            outputs.append(self._exon_groups[i].consensus('leftmost'))
         elif z == finish:
            #len(self._exon_groups)-1:
            outputs.append(self._exon_groups[i].consensus('rightmost'))
         else:
            outputs.append(self._exon_groups[i].consensus('internal'))
         z += 1
      v = [seqtools.structure.transcript.Exon(x) for x in outputs]
      v[0].set_leftmost()
      v[-1].set_rightmost()
      return v
1248823
def load_alleles_dict():
    
    alleles = load_alleles()
    result = {}
    for allele in alleles:
        for name in {allele.name}.union(allele.synonyms):
            result[name] = allele
    return result
743969
def getgenes(args):
    
    p = OptionParser(getgenes.__doc__)
    p.add_option("--prefix", default="gbout",
            help="prefix of output files [default: %default]")
    p.add_option("--nopep", default=False, action="store_true",
            help="Only get cds and bed, no pep [default: %default]")
    filenames, accessions, idfile, opts, args = preparegb(p, args)
    prefix = opts.prefix

    GenBank(filenames=filenames, accessions=accessions, idfile=idfile).\
        write_genes(output=prefix, individual=opts.individual, \
        pep=(not opts.nopep))

    if opts.individual:
        logging.debug("Output written dir {0}".format(prefix))
    elif opts.nopep:
        logging.debug("Output written to {0}.bed, {0}.cds".format(prefix,))
    else:
        logging.debug("Output written to {0}.bed, {0}.cds, {0}.pep".format(prefix,))
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
572992
def genes_with_a_representative_structure(self):
        """"""
        tmp = DictList(x for x in self.genes if x.protein.representative_structure)
        return DictList(y for y in tmp if y.protein.representative_structure.structure_file)
532956
def get_gene2binvec(self):
        """"""
        _sec2chr = self.sec2chr
        return {g:[s in s2gos for s in _sec2chr] for g, s2gos in self.gene2section2gos.items()}
21394
def _get_vep_transcript(self, transcript_info):
        
        transcript = Transcript(
                hgnc_symbol = transcript_info.get('SYMBOL'),
                transcript_id = transcript_info.get('Feature'),
                ensembl_id = transcript_info.get('Gene'),
                biotype = transcript_info.get('BIOTYPE'),
                consequence = transcript_info.get('Consequence'),
                strand = transcript_info.get('STRAND'),
                sift = transcript_info.get('SIFT'),
                polyphen = transcript_info.get('PolyPhen'),
                exon = transcript_info.get('EXON'),
                HGVSc = transcript_info.get('HGVSc'),
                HGVSp = transcript_info.get('HGVSp'),
                GMAF = transcript_info.get('GMAF'),
                ExAC_MAF = transcript_info.get('ExAC_MAF')
            )
        return transcript
347685
def canonical_transcripts(gtf, out_file):
    
    if file_exists(out_file):
        return out_file
    db = get_gtf_db(gtf)
    with file_transaction(out_file) as tx_out_file:
        with open(tx_out_file, "w") as out_handle:
            for gene in db.features_of_type('gene'):
                exon_list = []
                for ti, transcript in enumerate(db.children(gene, level=1)):
                    cds_len = 0
                    total_len = 0
                    exons = list(db.children(transcript, level=1))
                    for exon in exons:
                        exon_length = len(exon)
                        if exon.featuretype == 'CDS':
                            cds_len += exon_length
                        total_len += exon_length

                    exon_list.append((cds_len, total_len, transcript, exons))

                # If we have CDS, then use the longest coding transcript
                if max(i[0] for i in exon_list) > 0:
                    best = sorted(exon_list)[0]
                # Otherwise, just choose the longest
                else:
                    best = sorted(exon_list, key=lambda x: x[1])[0]
                for exon in db.children(best[2], level=1):
                    out_handle.write(str(exon) + "\n")
    return out_file
839679
def tx2genedict(gtf, keep_version=False):
    
    d = {}
    with open_gzipsafe(gtf) as in_handle:
        for line in in_handle:
            if "gene_id" not in line or "transcript_id" not in line:
                continue
            geneid = line.split("gene_id")[1].split(" ")[1]
            geneid = _strip_non_alphanumeric(geneid)
            txid = line.split("transcript_id")[1].split(" ")[1]
            txid = _strip_non_alphanumeric(txid)
            if keep_version and "transcript_version" in line:
                txversion = line.split("transcript_version")[1].split(" ")[1]
                txversion = _strip_non_alphanumeric(txversion)
                txid  += "." + txversion
            if has_transcript_version(line) and not keep_version:
                txid = _strip_feature_version(txid)
                geneid = _strip_feature_version(geneid)
            d[txid] = geneid
    return d