Skip to content

Working with sequences

Mason M Lai edited this page Mar 29, 2017 · 2 revisions

A sequence is simply a string of nucleotides coupled with a name. The bio library has classes to represent two types of sequences: FASTA records and FASTQ records.

Fasta sequences

Constructing a FASTA sequence is easy.

FastaSequence fasta = new FastaSequence("ExampleName", "AGGTAGGCTTANTAGGCT");

The corresponding FASTA file record is

>ExampleName
AGGTAGGCTTANTAGGCT

and you can obtain this String with

fasta.toFormattedString();

FASTQ sequences

Constructing a FASTQ sequence requires either a byte array of quality scores,

FastqSequence fastq = new FastqSequence("ExampleName", "AGGTAGGCTT",
        new byte[] {35, 40, 40, 35, 2, 2, 30, 30, 30, 40});

or the corresponding String and an encoding scheme.

FastqSequence fastq = new FastqSequence("ExampleName", "AGGTAGGCTT", "DIID##???I",
        PhredEncoding.SANGER);

See the FASTQ format Wikipedia page for information on different Phred encodings.

Reading and writing files

It's unlikely that you will want to construct your own FASTQ sequences from scratch. It's more likely that you'll read the sequences from a file and do some sort of operation on them. There are parsers for both FASTA and FASTQ records. For example, the following code

  1. reads a FASTQ file at /example/fastqPath.fq
  2. ignores all records containing a base with a quality score less than ten
  3. takes the reverse complement of the remaining records
  4. converts each record to a String suitable for printing to a FASTQ file
  5. prints the Strings to standard out
Path p = Paths.get("/example/fastqPath.fq");
try (FastqParser fp = new FastqParser(p, PhredEncoding.ILLUMINA_13)) {
    fp.stream()
        .filter(x -> !x.hasAnyBaseWithQualityLessThan((byte) 10))
        .map(FastqSequence::reverseComplement)
        .map(x -> x.toFormattedString(PhredEncoding.ILLUMINA_13))
        .forEach(System.out::print);
}

If you're more comfortable using iterators rather than streams, you can do the following:

Path p = Paths.get("/example/fastqPath.fq");
try (FastqParser fp = new FastqParser(p, PhredEncoding.ILLUMINA_13)) {
    while (fp.hasNext()) {
        FastqSequence fastq = fp.next();
        if (fastq.hasAnyBaseWithQualityLessThan((byte) 10)) {
            System.out.print(fastq.reverseComplement()
                                  .toFormattedString(PhredEncoding.ILLUMINA_13));
        }
    }
}

Clone this wiki locally