Check that the FASTA and SEQRES sequences agree (they sometimes differ)
163149
def _validate_fasta_vs_seqres(self):
        ''''''
        pdb_id = self.pdb_id
        for chain_id, sequence in self.pdb.seqres_sequences.iteritems():
            if str(sequence) != self.FASTA[pdb_id][chain_id]:
                if self.pdb_id in use_seqres_sequence_for_fasta_sequence:
                    self.FASTA.replace_sequence(self.pdb_id, chain_id, str(sequence))
                elif self.pdb_id in use_fasta_sequence_for_seqres_sequence:
                    self.pdb.seqres_sequences[chain_id] = Sequence.from_sequence(chain_id, self.FASTA[pdb_id][chain_id], self.sequence_types[chain_id])
                    sequence = self.FASTA[pdb_id][chain_id]
                if str(sequence) != self.FASTA[pdb_id][chain_id]:
                    raise colortext.Exception("The SEQRES and FASTA sequences disagree for chain %s in %s. This can happen but special-case handling (use_seqres_sequence_for_fasta_sequence) should be added to the file containing the %s class." % (chain_id, pdb_id, self.__class__.__name__))
1197558
private static boolean isValidSequence(List<ExpandedPair> pairs) {
    for (int[] sequence : FINDER_PATTERN_SEQUENCES) {
      if (pairs.size() > sequence.length) {
        continue;
      }

      boolean stop = true;
      for (int j = 0; j < pairs.size(); j++) {
        if (pairs.get(j).getFinderPattern().getValue() != sequence[j]) {
          stop = false;
          break;
        }
      }

      if (stop) {
        return true;
      }
    }

    return false;
  }
527361
def is_fasta(filename):
    
    if re.search("\.fa*s[ta]*$", filename, flags=re.I):
        return True
    elif re.search("\.fa$", filename, flags=re.I):
        return True
    else:
        return False
35959
def sam_to_fastq(sam):
    ''''''
    name = sam.qname
    if sam.is_read1:
        name += '/1'
    elif sam.is_read2:
        name += '/2'
    else:
        raise Error('Read ' + name + ' must be first or second of pair according to flag. Cannot continue')

    seq = pyfastaq.sequences.Fastq(name, common.decode(sam.seq), common.decode(sam.qual))
    if sam.is_reverse:
        seq.revcomp()

    return seq
1308240
def extract_sequences(self, ids, new_path=None):
        """"""
        # Temporary path #
        if new_path is None: new_fasta = self.__class__(new_temp_path())
        elif isinstance(new_path, FASTA): new_fasta = new_path
        else:                new_fasta = self.__class__(new_path)
        # Do it #
        new_fasta.create()
        for seq in self:
            if seq.id in ids: new_fasta.add_seq(seq)
        new_fasta.close()
        return new_fasta
756761
def get_seqs_fasta(seqs, names, out_fa):
    """"""
    with open(out_fa, 'w') as fa_handle:
        for s, n in itertools.izip(seqs, names):
            print(">cx{1}-{0}\n{0}".format(s, n), file=fa_handle)
    return out_fa
1221436
def subseq(start_offset=0, end_offset=None):
    
    def _(sequence):
        return sequence.subseq(start_offset, end_offset)
    return _
50909
def match_sequence(self, tokens, item):
        """"""
        tail = None
        if len(tokens) == 2:
            series_type, matches = tokens
        else:
            series_type, matches, tail = tokens
        self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)")
        if tail is None:
            self.add_check("_coconut.len(" + item + ") == " + str(len(matches)))
        else:
            self.add_check("_coconut.len(" + item + ") >= " + str(len(matches)))
            if tail != wildcard:
                if len(matches) > 0:
                    splice = "[" + str(len(matches)) + ":]"
                else:
                    splice = ""
                self.assign_to_series(tail, series_type, item + splice)
        self.match_all_in(matches, item)
661743
def fasta(self):
        """"""
        max_line_length = 79
        fasta_str = '>{0}:{1}|PDBID|CHAIN|SEQUENCE\n'.format(
            self.parent.id.upper(), self.id)
        seq = self.sequence
        split_seq = [seq[i: i + max_line_length]
                     for i in range(0, len(seq), max_line_length)]
        for seq_part in split_seq:
            fasta_str += '{0}\n'.format(seq_part)
        return fasta_str
336808
def are_token_parallel(sequences: Sequence[Sized]) -> bool:
    
    if not sequences or len(sequences) == 1:
        return True
    return all(len(s) == len(sequences[0]) for s in sequences)
1148833
static Matcher sequenceWithFalseIsFalse(Matcher matcher) {
    if (matcher instanceof SeqMatcher) {
      for (Matcher m : matcher.<SeqMatcher>as().matchers()) {
        if (m instanceof FalseMatcher) {
          return FalseMatcher.INSTANCE;
        }
      }
    }
    return matcher;
  }
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
444200
def get_seqs_type(seqs):
    
    region_p = re.compile(r'^(.+):(\d+)-(\d+)$')
    if isinstance(seqs, Fasta):
        return "fasta"
    elif isinstance(seqs, list):
        if len(seqs) == 0:
            raise ValueError("empty list of sequences to scan")
        else:
            if region_p.search(seqs[0]):
                return "regions"
            else:
                raise ValueError("unknown region type")
    elif isinstance(seqs, str) or isinstance(seqs, unicode):
        if os.path.isfile(seqs):
            ftype = determine_file_type(seqs)
            if ftype == "unknown":
                raise ValueError("unknown type")
            elif ftype == "narrowpeak":
                raise ValueError("narrowPeak not yet supported in this function")
            else:
                return ftype + "file"
        else:
            raise ValueError("no file found with name {}".format(seqs))
    else:
        raise ValueError("unknown type {}".format(type(seqs).__name__))
570326
public boolean matches(String seq) {
        return queue.regionMatches(true, pos, seq, 0, seq.length());
    }
321294
def similarity(self, other):
        """"""
        ratio = SequenceMatcher(a=self.value, b=other.value).ratio()
        similarity = self.Similarity(ratio)
        return similarity
9428
def compare_seqs(seqs):
    
    A, B, ignore_gaps = seqs
    a, b = A[1], B[1] # actual sequences
    if len(a) != len(b):
        print('# reads are not the same length', file=sys.stderr)
        exit()
    if ignore_gaps is True:
        pident = calc_pident_ignore_gaps(a, b)
    else:
        pident = calc_pident(a, b)
    return A[0], B[0], pident
916906
def diff(args):
    
    from jcvi.utils.table import banner

    p = OptionParser(diff.__doc__)
    p.add_option("--ignore_case", default=False, action="store_true",
            help="ignore case when comparing sequences [default: %default]")
    p.add_option("--ignore_N", default=False, action="store_true",
            help="ignore N and X's when comparing sequences [default: %default]")
    p.add_option("--ignore_stop", default=False, action="store_true",
            help="ignore stop codon when comparing sequences [default: %default]")
    p.add_option("--rc", default=False, action="store_true",
            help="also consider reverse complement [default: %default]")
    p.add_option("--quiet", default=False, action="store_true",
            help="don't output comparison details [default: %default]")

    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    afasta, bfasta = args

    afastan = len(Fasta(afasta))
    bfastan = len(Fasta(bfasta))

    if afastan == bfastan:
        print(green("Two sets contain the same number of sequences ({0}, {1})".\
                format(afastan, bfastan)))
    else:
        print(red("Two sets contain different number of sequences ({0}, {1})".\
                format(afastan, bfastan)))

    ah = SeqIO.parse(afasta, "fasta")
    bh = SeqIO.parse(bfasta, "fasta")

    problem_ids = []
    for arec, brec in zip(ah, bh):

        if opts.ignore_stop:
            arec.seq = arec.seq.rstrip("*")
            brec.seq = brec.seq.rstrip("*")

        asize, bsize = len(arec), len(brec)

        if not opts.quiet:
            print(banner(str(arec), [str(brec)]))
            if asize == bsize:
                print(green("Two sequence size match (%d)" % asize))
            else:
                print(red("Two sequence size do not match (%d, %d)" % (asize, bsize)))

        # print out the first place the two sequences diff
        fd = print_first_difference(arec, brec, ignore_case=opts.ignore_case,
                ignore_N=opts.ignore_N, rc=opts.rc, report_match=not opts.quiet)
        if not fd:
            logging.error("Two sets of sequences differ at `{0}`".format(arec.id))
            problem_ids.append("\t".join(str(x) for x in (arec.id, asize, bsize,
                    abs(asize - bsize))))

    if problem_ids:
        print(red("A total of {0} records mismatch.".format(len(problem_ids))))
        fw = must_open("Problems.ids", "w")
        print("\n".join(problem_ids), file=fw)