Find all instances of the codons in 'codons' in the given sequence.

    seq: A Bio.Seq.Seq instance.
    codons: A set of codon strings.

    Return: a generator yielding matching codon offsets.
961494
def findCodons(seq, codons):
    
    seqLen = len(seq)
    start = 0
    while start < seqLen:
        triplet = str(seq[start:start + 3])
        if triplet in codons:
            yield start
        start = start + 3
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)
296321
def get_sequences(self, chr, coords):
            
        # Check if we have an index_dir
        if not self.index_dir:
            print("Index dir is not defined!")
            sys.exit()

        # retrieve all information for this specific sequence
        fasta_file = self.fasta_file[chr]
        index_file = self.index_file[chr]
        line_size = self.line_size[chr]
        total_size = self.size[chr]
        index = open(index_file, "rb")
        fasta = open(fasta_file)
        
        seqs = []
        for coordset in coords:
            seq = ""
            for (start,end) in coordset: 
                if start > total_size:
                    raise ValueError("%s: %s, invalid start, greater than sequence length!" % (chr,start))
            
                if start < 0:
                    raise ValueError("Invalid start, < 0!")
                
                if end > total_size:
                    raise ValueError("Invalid end, greater than sequence length!")


                seq += self._read(index, fasta, start, end, line_size)
            seqs.append(seq)
        index.close()
        fasta.close()

        return seqs
1168829
def complete(self):
        
        return (
            self.contains_start_codon and
            self.contains_stop_codon and
            self.coding_sequence is not None and
            len(self.coding_sequence) % 3 == 0
        )
368673
def sequence(self, per_exon=False):
        
        db = self.db
        if not per_exon:
            start = self.txStart + 1
            return _sequence(db, self.chrom, start, self.txEnd)
        else:
            # TODO: use same strategy as cds_sequence to reduce # of requests.
            seqs = []
            for start, end in self.exons:
                seqs.append(_sequence(db, self.chrom, start + 1, end))
            return seqs
563233
def codon2aa(codon, trans_table):
    
    return Seq(''.join(codon), IUPAC.ambiguous_dna).translate(table = trans_table)[0]
63673
def get_all(self, seq_set: SequenceSet) \
            -> Sequence[Tuple[int, CachedMessage]]:
        
        if seq_set.uid:
            all_uids = seq_set.flatten(self.max_uid) & self._uids
            return [(seq, self._cache[uid])
                    for seq, uid in enumerate(self._sorted, 1)
                    if uid in all_uids]
        else:
            all_seqs = seq_set.flatten(self.exists)
            return [(seq, self._cache[uid])
                    for seq, uid in enumerate(self._sorted, 1)
                    if seq in all_seqs]
384834
def dna_to_re(seq):
    

    seq = seq.replace('K', '[GT]')
    seq = seq.replace('M', '[AC]')
    seq = seq.replace('R', '[AG]')
    seq = seq.replace('Y', '[CT]')
    seq = seq.replace('S', '[CG]')
    seq = seq.replace('W', '[AT]')
    seq = seq.replace('B', '[CGT]')
    seq = seq.replace('V', '[ACG]')
    seq = seq.replace('H', '[ACT]')
    seq = seq.replace('D', '[AGT]')
    seq = seq.replace('X', '[GATC]')
    seq = seq.replace('N', '[GATC]')

    return re.compile(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)
580332
def sequences(self):
        
        seqs = [x.sequence for x in self._molecules if hasattr(x, 'sequence')]
        return seqs
45048
def scan_sequence(self, frame, direction):
        
        orf_start = None
        for c, index in self.codons(frame):
            if (c not in self.stop and (c in self.start or not self.start)
                and orf_start is None):
                orf_start = index
            elif c in self.stop and orf_start is not None:
                self._update_longest(orf_start, index + 3, direction, frame)
                orf_start = None

        if orf_start is not None:
            self._update_longest(orf_start, index + 3, direction, frame)
1013855
def get_sequences(options, fasta_file_contents):
    ''' 
    '''
    errors = []
    fasta_files_str = ", ".join(fasta_file_contents.keys())
    fasta_records = None
    reverse_mapping = {}

    try:
        fasta_records, reverse_mapping = parse_FASTA_files(options, fasta_file_contents)
        if not fasta_records:
            errors.append("No protein sequences found in the FASTA file(s) %s." % fasta_files_str)
    except Exception, e:
        e = '\n'.join([l for l in traceback.format_exc(), str('e') if l.strip()])
        errors.append("Error parsing FASTA file(s) %s:\n%s" % (fasta_files_str, str(e)))

    if not fasta_records:
        return None, {}, errors

    colorprinter.message('Found %d protein sequence(s).' % len(fasta_records))
    return fasta_records, reverse_mapping, errors
146192
def sequences(self):
        """"""
        lines = Lines()
        lines.add(0, '@cython.final')
        lines.add(0, 'cdef class Sequences(object):')
        for subseqs in self.model.sequences:
            lines.add(1, 'cdef public %s %s'
                         % (objecttools.classname(subseqs), subseqs.name))
        if getattr(self.model.sequences, 'states', None) is not None:
            lines.add(1, 'cdef public StateSequences old_states')
            lines.add(1, 'cdef public StateSequences new_states')
        for subseqs in self.model.sequences:
            print('        - %s' % subseqs.name)
            lines.add(0, '@cython.final')
            lines.add(0, 'cdef class %s(object):'
                         % objecttools.classname(subseqs))
            for seq in subseqs:
                ctype = 'double' + NDIM2STR[seq.NDIM]
                if isinstance(subseqs, sequencetools.LinkSequences):
                    if seq.NDIM == 0:
                        lines.add(1, 'cdef double *%s' % seq.name)
                    elif seq.NDIM == 1:
                        lines.add(1, 'cdef double **%s' % seq.name)
                        lines.add(1, 'cdef public int len_%s' % seq.name)
                else:
                    lines.add(1, 'cdef public %s %s' % (ctype, seq.name))
                lines.add(1, 'cdef public int _%s_ndim' % seq.name)
                lines.add(1, 'cdef public int _%s_length' % seq.name)
                for idx in range(seq.NDIM):
                    lines.add(1, 'cdef public int _%s_length_%d'
                                 % (seq.name, idx))
                if seq.NUMERIC:
                    ctype_numeric = 'double' + NDIM2STR[seq.NDIM+1]
                    lines.add(1, 'cdef public %s _%s_points'
                                 % (ctype_numeric, seq.name))
                    lines.add(1, 'cdef public %s _%s_results'
                                 % (ctype_numeric, seq.name))
                    if isinstance(subseqs, sequencetools.FluxSequences):
                        lines.add(1, 'cdef public %s _%s_integrals'
                                     % (ctype_numeric, seq.name))
                        lines.add(1, 'cdef public %s _%s_sum'
                                     % (ctype, seq.name))
                if isinstance(subseqs, sequencetools.IOSequences):
                    lines.extend(self.iosequence(seq))
            if isinstance(subseqs, sequencetools.InputSequences):
                lines.extend(self.load_data(subseqs))
            if isinstance(subseqs, sequencetools.IOSequences):
                lines.extend(self.open_files(subseqs))
                lines.extend(self.close_files(subseqs))
                if not isinstance(subseqs, sequencetools.InputSequence):
                    lines.extend(self.save_data(subseqs))
            if isinstance(subseqs, sequencetools.LinkSequences):
                lines.extend(self.set_pointer(subseqs))
        return lines
368070
def codons(self, frame):
        
        start = frame
        while start + 3 <= self.size:
            yield self.sequence[start : start + 3], start
            start += 3
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
1266284
def view_seq(self, seq):
        
        log.debug('Viewing sequence %s', seq.name)
        self.cur_seq = None
        self.pages_tabw.setCurrentIndex(2)
        self.seq_name_le.setText(seq.name)
        self.seq_prj_le.setText(seq.project.name)
        self.seq_desc_pte.setPlainText(seq.description)

        shotrootdata = treemodel.ListItemData(['Name', "Description", "Duration", "Start", "End"])
        shotrootitem = treemodel.TreeItem(shotrootdata)
        for shot in seq.shot_set.all():
            shotdata = djitemdata.ShotItemData(shot)
            treemodel.TreeItem(shotdata, shotrootitem)
        self.seq_shot_model = treemodel.TreeModel(shotrootitem)
        self.seq_shot_tablev.setModel(self.seq_shot_model)
        self.cur_seq = seq
789791
def build(cls, seqs: Iterable[int], uid: bool = False) -> 'SequenceSet':
        
        seqs_list = sorted(set(seqs))
        groups: List[Union[int, Tuple[int, int]]] = []
        group: Union[int, Tuple[int, int]] = seqs_list[0]
        for i in range(1, len(seqs_list)):
            group_i = seqs_list[i]
            if isinstance(group, int):
                if group_i == group + 1:
                    group = (group, group_i)
                else:
                    groups.append(group)
                    group = group_i
            elif isinstance(group, tuple):
                if group_i == group[1] + 1:
                    group = (group[0], group_i)
                else:
                    groups.append(group)
                    group = group_i
        groups.append(group)
        return SequenceSet(groups, uid)