obtain the sequence for a transcript from ensembl
421485
def get_exon_ranges_for_transcript(self, transcript_id):
        
        
        headers = {"content-type": "application/json"}
        
        self.attempt = 0
        ext = "/overlap/id/{}?feature=exon".format(transcript_id)
        r = self.ensembl_request(ext, headers)
        
        exon_ranges = []
        for exon in json.loads(r):
            if exon["Parent"] != transcript_id:
                continue
            
            start = exon["start"]
            end = exon["end"]
            
            exon_ranges.append((start, end))
        
        return exon_ranges
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
1214775
def get_transcript(self, gene_pk, refseq_id):
        ""
        if not refseq_id:
            return
        transcript_pk = self.transcripts.get(refseq_id)
        if transcript_pk:
            return transcript_pk
        gene = Gene(pk=gene_pk)
        transcript = Transcript(refseq_id=refseq_id, gene=gene)
        try:
            transcript.save()
        except IntegrityError:
            transcript = Transcript.objects.get(refseq_id=refseq_id, gene=gene)
        self.transcripts[refseq_id] = transcript.pk
        return transcript.pk
1299613
def sequence(self):
        
        seq = [x.mol_code for x in self._monomers]
        return ' '.join(seq)
31071
def from_seqfeature(s, **kwargs):
    
    source = s.qualifiers.get('source', '.')[0]
    score = s.qualifiers.get('score', '.')[0]
    seqid = s.qualifiers.get('seqid', '.')[0]
    frame = s.qualifiers.get('frame', '.')[0]
    strand = _feature_strand[s.strand]

    # BioPython parses 1-based GenBank positions into 0-based for use within
    # Python.  We need to convert back to 1-based GFF format here.
    start = s.location.start.position + 1
    stop = s.location.end.position
    featuretype = s.type
    id = s.id
    attributes = dict(s.qualifiers)
    attributes.pop('source', '.')
    attributes.pop('score', '.')
    attributes.pop('seqid', '.')
    attributes.pop('frame', '.')
    return Feature(seqid, source, featuretype, start, stop, score, strand,
                   frame, attributes, id=id, **kwargs)
254664
def get_genomic_seq_for_transcript(self, transcript_id, expand):
        
        
        headers = {"content-type": "application/json"}
        
        self.attempt = 0
        ext = "/sequence/id/{0}?type=genomic;expand_3prime={1};expand_5prime={1}".format(transcript_id, expand)
        r = self.ensembl_request(ext, headers)
        
        gene = json.loads(r)
        
        seq = gene["seq"]
        seq_id = gene["id"]
        
        if seq_id != transcript_id:
            raise ValueError("ensembl gave the wrong transcript")
        
        desc = gene["desc"].split(":")
        chrom = desc[2]
        start = int(desc[3]) + expand
        end = int(desc[4]) - expand
        strand_temp = int(desc[5])
        
        strand = "+"
        if strand_temp == -1:
            strand = "-"
        
        return (chrom, start, end, strand, seq)
754595
def slice_sequence(self,start,end,directionless=False):
     
     if end > self.length: end = self.length
     if start < 0: start = 0
     if not directionless and self.direction == '-': 
        newend = self.length-start
        newstart = self.length-end
        end = newend
        start = newstart
     #find the sequence length
     l = self.length
     indexstart = start
     indexend = end
     ns = []
     tot = 0
     for r in self._rngs:
        tot += r.length
        n = r.copy()
        if indexstart > r.length:
           indexstart-=r.length
           continue
        n.start = n.start+indexstart
        if tot > end:
           diff = tot-end
           n.end -= diff
           tot = end
        indexstart = 0
        ns.append(n)
        if tot == end: break
     if len(ns)==0: return None
     return Transcript(ns,self._options)
930542
public String getProteinSequenceString() {

		if (sequence != null)
			return sequence.toString();

		StringBuilder builder = new StringBuilder();
		for (Atom a : reprAtoms)
			// This method preferred over getChemComp.getOneLetterCode because
			// it returns always X for Unknown residues
			builder.append(StructureTools.get1LetterCode(a.getGroup()
					.getPDBName()));

		return builder.toString();
	}
394493
def sequence_type(seq):
    '''

    '''
    if isinstance(seq, coral.DNA):
        material = 'dna'
    elif isinstance(seq, coral.RNA):
        material = 'rna'
    elif isinstance(seq, coral.Peptide):
        material = 'peptide'
    else:
        raise ValueError('Input was not a recognized coral.sequence object.')
    return material
486951
def ensembl_to_kegg(organism,kegg_db):
    
    print("KEGG API: http://rest.genome.jp/link/"+kegg_db+"/"+organism)
    sys.stdout.flush()
    kegg_ens=urlopen("http://rest.genome.jp/link/"+kegg_db+"/"+organism).read()
    kegg_ens=kegg_ens.split("\n")
    final=[]
    for i in kegg_ens:
        final.append(i.split("\t"))
    df=pd.DataFrame(final[0:len(final)-1])[[0,1]]
    ens_id=pd.DataFrame(df[1].str.split(":").tolist())[1]
    df=pd.concat([df,ens_id],axis=1)
    df.columns=['KEGGid','ensDB','ENSid']
    df=df[['KEGGid','ENSid']]
    return df
703495
def cli(ctx, feature_id, organism="", sequence=""):
    
    return ctx.gi.annotations.get_feature_sequence(feature_id, organism=organism, sequence=sequence)
654724
def get_sequence(queries,fap=None,fmt='fasta',
            organism_taxid=9606,
                 test=False):
    
    url = 'http://www.ebi.ac.uk/Tools/dbfetch/dbfetch'
    params = {
    'id':' '.join(queries),
    'db':'uniprotkb',
    'organism':organism_taxid,    
    'format':fmt,
    'style':'raw',
    'Retrieve':'Retrieve',
    }
    response = requests.get(url, params=params)
    if test:
        print(response.url)
    if response.ok:
        if not fap is None:
            with open(fap,'w') as f:
                f.write(response.text)
            return fap
        else:
            return response.text            
    else:
        print('Something went wrong ', response.status_code)
719705
def dense_to_human_readable(dense_repr: Sequence[Sequence[int]], index_to_label: Dict[int, str]) -> List[List[str]]:
    

    transcripts = []
    for dense_r in dense_repr:
        non_empty_phonemes = [phn_i for phn_i in dense_r if phn_i != 0]
        transcript = [index_to_label[index] for index in non_empty_phonemes]
        transcripts.append(transcript)

    return transcripts
130623
def transcripts(self, contig=None, strand=None):
        
        transcript_ids = self.transcript_ids(contig=contig, strand=strand)
        return [
            self.transcript_by_id(transcript_id)
            for transcript_id in transcript_ids
        ]
860718
def _get_genes(self, variant):
        
        ensembl_ids = []
        hgnc_symbols = []
        
        for transcript in variant.transcripts:
            if transcript.ensembl_id:
                ensembl_ids.append(transcript.ensembl_id)
            if transcript.hgnc_symbol:
                hgnc_symbols.append(transcript.hgnc_symbol)
        
        genes = get_gene_info(
                        ensembl_ids=ensembl_ids, 
                        hgnc_symbols=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
365664
def cli(ctx, transcript_id, organism="", sequence=""):
    
    return ctx.gi.annotations.duplicate_transcript(transcript_id, organism=organism, sequence=sequence)