Reverse complement a sequence.

    :param sequence: Sequence to reverse complement
    :type sequence: str
    :param material: dna, rna, or peptide.
    :type material: str
185169
def reverse_complement(sequence, material):
    '''
    '''
    code = dict(COMPLEMENTS[material])
    reverse_sequence = sequence[::-1]
    return ''.join([code[str(base)] for base in reverse_sequence])
227559
def translate_codons(sequence):
    '''
    '''
    return ''.join([gencode.get(sequence[3*i:3*i+3],'X') for i in range(len(sequence)//3)])
393673
def validate_sequence(sequence: str, sequence_is_as_nucleotide=True):
    

    tmp_seq = tempfile.NamedTemporaryFile(mode="wb+", delete=False)

    if len(str(sequence).strip()) == 0:
        raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_ERROR_MSG)

    if str(sequence).strip()[0] != ">":
        tmp_seq.write(">seq1\n".encode())

    tmp_seq.write(sequence.encode())
    tmp_seq.close()

    records = SeqIO.index(tmp_seq.name, "fasta")
    record_count = len(records)

    if record_count == 0:
        raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_ERROR_MSG)

    if record_count > blast_settings.BLAST_MAX_NUMBER_SEQ_IN_INPUT:
        raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_MAX_SEQ_NUMB_ERROR_MSG)

    # read query sequence from temporary file
    first_sequence_list_in_file = SeqIO.parse(tmp_seq.name, "fasta")

    for sequence in first_sequence_list_in_file:

        if len(sequence.seq) <= 10:
            raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_TOO_SHORT_ERROR_MSG)

        if sequence_is_as_nucleotide:
            check_allowed_letters(str(sequence.seq), ALLOWED_NUCL)
        else:
            check_allowed_letters(str(sequence.seq), ALLOWED_AMINOACIDS)

    return tmp_seq
329380
def filter_sequences(self, seq_type):
        
        return DictList(x for x in self.sequences if isinstance(x, seq_type))
535197
def reverse_complement( self ):
        
        rval = copy( self )
        # Conveniently enough, reversing rows and columns is exactly what we
        # want, since this results in A swapping with T and C swapping with G.
        rval.values = self.values[::-1,::-1].copy()
        return rval
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
1113790
def _coord(sequence, start, mirna, precursor, iso):
    
    dif = abs(mirna[0] - start)
    if start < mirna[0]:
        iso.t5 = sequence[:dif].upper()
    elif start > mirna[0]:
        iso.t5 = precursor[mirna[0] - 1:mirna[0] - 1 + dif].lower()
    elif start == mirna[0]:
        iso.t5 = "NA"
    if dif > 4:
        logger.debug("start > 3 %s %s %s %s %s" % (start, len(sequence), dif, mirna, iso.format()))
        return None

    end = start + (len(sequence) - len(iso.add)) - 1
    dif = abs(mirna[1] - end)
    if iso.add:
        sequence = sequence[:-len(iso.add)]
    # if dif > 3:
    #    return None
    if end > mirna[1]:
        iso.t3 = sequence[-dif:].upper()
    elif end < mirna[1]:
        iso.t3 = precursor[mirna[1] - dif:mirna[1]].lower()
    elif end == mirna[1]:
        iso.t3 = "NA"
    if dif > 4:
        logger.debug("end > 3 %s %s %s %s %s" % (len(sequence), end, dif, mirna, iso.format()))
        return None
    logger.debug("%s %s %s %s %s %s" % (start, len(sequence), end, dif, mirna, iso.format()))
    return True
399584
def locate_primers(sequences, forward_primer, reverse_primer,
                   reverse_complement, max_hamming_distance):
    
    forward_loc = None
    reverse_loc = None
    seq_length = None

    # Reverse complement the reverse primer, if appropriate
    if reverse_complement:
        reverse_primer = reverse_primer.reverse_complement()

    forward_aligner = PrimerAligner(forward_primer)
    reverse_aligner = PrimerAligner(reverse_primer)

    for i, sequence in enumerate(sequences):
        if seq_length is None:
            seq_length = len(sequence)
        elif len(sequence) != seq_length:
            raise ValueError(("Sequence Length Heterogeneity: {0} != {1}. "
                              "Is this an alignment?").format(
                                  len(sequence), seq_length))
        index_map = ungap_index_map(sequence.seq)
        if forward_loc is None:
            ham_dist, start, end = forward_aligner.align(sequence.seq.ungap())
            if ham_dist <= max_hamming_distance:
                forward_loc = index_map[start], index_map[end]
                logging.info("Forward in sequence %d: indexes %d to %d", i + 1,
                             *forward_loc)
        if reverse_loc is None:
            ham_dist, start, end = reverse_aligner.align(sequence.seq.ungap())
            if ham_dist <= max_hamming_distance:
                reverse_loc = index_map[start], index_map[end]
                logging.info("Reverse in sequence %d: indexes %d to %d", i + 1,
                             *reverse_loc)
        if forward_loc and reverse_loc:
            # Both found
            # Check order
            if forward_loc[0] > reverse_loc[0]:
                raise PrimerOrderError(forward_loc[0], reverse_loc[0])
            return forward_loc, reverse_loc
        else:
            logging.debug(
                "Sequence %d: %d/2 primers found", i + 1,
                sum(j is not None for j in (forward_loc, reverse_loc)))

    # Did not find either the forward or reverse primer:
    if not forward_loc:
        raise PrimerNotFound(forward_primer)
    else:
        raise PrimerNotFound(reverse_primer)
165069
def from_sequence(cls, seq, order=None, **kwargs):
        """"""
        for arg in seq:
            yield cls(arg, order=order, **kwargs)
343362
@SuppressWarnings("unchecked")
	protected <C extends Compound> Sequence<C> reverseSequence(Sequence<C> sequence) {
		if(getStrand() != Strand.NEGATIVE) {
			return sequence;
		}

		Sequence<C> reversed = new ReversedSequenceView<C>(sequence);
		// "safe" operation as we have tried to check this
		if(canComplement(sequence)) {
			Sequence<ComplementCompound> casted = (Sequence<ComplementCompound>) reversed;
			ComplementSequenceView<ComplementCompound> complement =
					new ComplementSequenceView<ComplementCompound>(casted);
			return (Sequence<C>)complement;
		}
		return reversed;
	}
368070
def codons(self, frame):
        
        start = frame
        while start + 3 <= self.size:
            yield self.sequence[start : start + 3], start
            start += 3
751811
def precursor_sequence(loci, reference):
    """"""
    region = "%s\t%s\t%s\t.\t.\t%s" % (loci[1], loci[2], loci[3], loci[4])
    precursor = pybedtools.BedTool(str(region), from_string=True).sequence(fi=reference, s=True)
    return open(precursor.seqfn).read().split("\n")[1]
154747
def cli(ctx, organism, sequence):
    
    return ctx.gi.annotations.set_sequence(organism, sequence)
124144
def seq_str(self):
        """"""

        if not self.seq:
            return None

        return ssbio.protein.sequence.utils.cast_to_str(self.seq)
257105
def get_sequence(self,ref):
    """"""
    strand = '+'
    if not self._options.direction:
      sys.stderr.write("WARNING: no strand information for the transcript\n")
    if self._options.direction: strand = self._options.direction
    seq = ''
    for e in [x.range for x in self.exons]:
      seq += str(ref[e.chr][e.start-1:e.end])
    if strand == '-':  seq = rc(seq)
    return Sequence(seq.upper())
487847
def from_sequence(cls, sequence, phos_3_prime=False):
        
        strand1 = NucleicAcidStrand(sequence, phos_3_prime=phos_3_prime)
        duplex = cls(strand1)
        return duplex
975465
def variant_matches_reference_sequence(variant, ref_seq_on_transcript, strand):
    
    if strand == "-":
        ref_seq_on_transcript = reverse_complement_dna(ref_seq_on_transcript)
    return ref_seq_on_transcript == variant.ref