Directly use the fasta format parser to load a sequence
The cogent3 parsers return standard Python data types. The iter_fasta_records() is a generator, so it yields one record at a time. Because I know there’s a single sequence in this file, I wrap the call with list and select the first record.
from cogent3.parse.fasta import iter_fasta_recordslabel, seq =list(iter_fasta_records("data/mycoplasma-genitalium.fa"))[0]label, seq[:10]
You can provide a converter that will transform the sequence data to the type you want. In this example, we use a cogent3 builtin to return a numpy array of unsigned 8-bit integers. We first get all the IUPAC characters for DNA and construct the converter. The converter maps an integer the provided characters in their order of occurrence in dna_alpha.
Directly use the genbank format parser to load a sequence and annotations
The cogent3 parsers return standard Python data types. The iter_genbank_records() is a generator, so it yields one record at a time. Because I know there’s a single sequence in this file, I wrap the call with list and select the first record.
from cogent3.parse.genbank import iter_genbank_recordslabel, seq, anns =list(iter_genbank_records("data/mycoplasma-genitalium.gb"))[0]label, seq[:10], anns.keys()
As the output indicates, variable anns is a dictionary. The features in the GenBank feature table are available as a list under the "features" key. (See getting GenBank features as primitives.)
Directly use the fastq format parser to load reads with quality scores
The iter_fastq_records() generator yields (label, sequence, quality) tuples for each record in a fastq file. By default both the sequence and quality strings are decoded to str.
from cogent3.parse.fastq import iter_fastq_recordsfor label, seq, qual in iter_fastq_records("data/fastq.txt"): ... # do your work here
To get a transformation of read quality into Phred scores, pass a converter built with make_qual_converter to get quality as a numpy.uint8 array. The scoring scheme can be selected by a PhredEncoding member or by name ("phred+33" or "phred+64", case insensitive).
from cogent3.core.alphabet import PhredEncoding, make_qual_converterqual_converter = make_qual_converter(PhredEncoding.PHRED_33)label, seq, qual =next(iter(iter_fastq_records("data/fastq.txt", qual_converter=qual_converter)))label, seq, qual
As with the fasta and genbank iterative parsers, a converter argument exists for providing a custom transformer to be applied to the sequence data too.
Loading sequence collections from a file or url
Loading aligned sequences
Any file in which the sequences have exactly the same length can be loaded as an alignment.
from cogent3 import load_aligned_seqsaln = load_aligned_seqs("data/long_testseqs.fasta", moltype="dna")type(aln)
cogent3.core.alignment.Alignment
Note
The load functions record the origin of the data in a .source attribute.
aln.source
'data/long_testseqs.fasta'
Loading unaligned sequences
Files containing sequences that may differ in length can be loaded using load_unaligned_seqs(), which returns a sequence collection.
from cogent3 import load_unaligned_seqsseqs = load_unaligned_seqs("data/long_testseqs.fasta", moltype="dna")type(seqs)
cogent3.core.alignment.SequenceCollection
Loading unaligned sequences from multiple files
You can create a single sequence collection containing sequences from all files in a directory that match a wildcard (or glob) pattern (e.g. "path/to/dir/*.<filename suffix>"). We load data from files ending with .fa using load_unaligned_seqs(). This approach can be taken for all supported sequence file formats.
from cogent3 import load_unaligned_seqsseqs = load_unaligned_seqs("data/*.fa", moltype="dna")seqs
0
I dna:chromosome chromosome:WBcel235:I:1:15072434:1 REF
4 x {min=150, median=299542.5, max=15072434} dna sequence collection
Note
The function limits loading to just one sequence per file.
Loading from a url
The cogent3 load functions support loading from a url. We load the above fasta file directly from GitHub.
from cogent3 import load_aligned_seqsaln = load_aligned_seqs("https://raw.githubusercontent.com/cogent3/cogent3/develop/doc/data/long_testseqs.fasta", moltype="dna",)
Discovering the supported file formats
Use available_seq_formats() to see the formats that load_seq(), load_aligned_seqs() and load_unaligned_seqs() can read. The “suffixes” column lists the filename suffixes that map to each format.
from cogent3 import available_seq_formatsavailable_seq_formats()
Specify a format by its name or a file by one of its suffixes.
name
suffixes
aligned
unaligned
c3h5a
c3h5a
True
False
c3h5s
c3h5s
True
False
c3h5u
c3h5u
False
True
clustal
aln, clustal
True
True
fasta
fa, faa, fasta, fna, mfa
True
True
gbseq
gbseq
True
True
gde
gde
True
True
genbank
gb, gbff, gbk, genbank
True
True
msf
msf
True
True
nexus
nex, nexus, nxs
True
True
paml
paml
True
True
phylip
phy, phylip
True
True
tinyseq
tinyseq
True
True
13 rows x 4 columns
Specifying the file format
The loading functions use the filename suffix to infer the file format. This can be overridden using the format argument.
from cogent3 import load_aligned_seqsaln = load_aligned_seqs("data/long_testseqs.fasta", moltype="dna", format_name="fasta")aln
from cogent3 import make_aligned_seqsdata = ["AATCG-A", "AATCGGA"]coll = make_aligned_seqs(data, moltype="dna")coll
0
seq_1
AATCGGA
seq_0
.....-.
2 x 7 dna alignment
Changing sequence labels on loading
Load a list of aligned nucleotide sequences, while specifying the DNA molecule type and stripping the comments from the label. In this example, we rename sequences by passing a function that removes everything after the first whitespace to the label_to_name parameter.
Making a sequence collection from standard python objects
This is done using make_unaligned_seqs(), which returns a SequenceCollection instance. The function arguments match those of make_aligned_seqs(). We demonstrate only for the case where the input data is a dict.
2 x {min=5, median=6.0, max=7} dna sequence collection
Loading sequences using format parsers
load_aligned_seqs() and load_unaligned_seqs() are just convenience interfaces to format parsers. It can sometimes be more effective to use the parsers directly, say when you don’t want to load everything into memory.
Loading FASTA sequences from an open file or list of lines
To load FASTA formatted sequences directly, you can use iter_fasta_records. This parser returns data as python strings.
Note
This returns the sequences as strings.
from cogent3.parse.fasta import iter_fasta_recordsseqs =list(iter_fasta_records("data/long_testseqs.fasta"))seqs
The FASTA label field is frequently overloaded, with different information fields present in the field and separated by some delimiter. This can be flexibly addressed using the LabelParser. By creating a custom label parser, we can decide which part we use as the sequence name. We show how to convert a field into something specific.
human <class 'cogent3.parse.fasta.RichLabel'>
chimp <class 'cogent3.parse.fasta.RichLabel'>
RichLabel objects have an Info object as an attribute, allowing specific reference to all the specified label fields.
from cogent3.parse.fasta import LabelParser, iter_fasta_recordsfasta_data = [">gi|10047090|ref|NP_055147.1| small muscle protein, X-linked [Homo sapiens]","MNMSKQPVSNVRAIQANINIPMGAFRPGAGQPPRRKECTPEVEEGVPPTSDEEKKPIPGAKKLPGPAVNL","SEIQNIKSELKYVPKAEQ",">gi|10047092|ref|NP_037391.1| neuronal protein [Homo sapiens]","MANRGPSYGLSREVQEKIEQKYDADLENKLVDWIILQCAEDIEHPPPGRAHFQKWLMDGTVLCKLINSLY","PPGQEPIPKISESKMAFKQMEQISQFLKAAETYGVRTTDIFQTVDLWEGKDMAAVQRTLMALGSVAVTKD",]label_to_name = LabelParser("%(ref)s", [[1, "gi", str], [3, "ref", str], [4, "description", str]], split_with="|",)for name, seq in iter_fasta_records(fasta_data, label_to_name=label_to_name):print(name)print(name.info.gi)print(name.info.description)
NP_055147.1
10047090
small muscle protein, X-linked [Homo sapiens]
NP_037391.1
10047092
neuronal protein [Homo sapiens]
Using a third-party plugin for sequence storage
Sequence collections and alignments have a .storage attribute which holds the underlying sequence data and provides basic functions for obtaining it. Users can install a third-party plugin which is customized for different types of sequence data. The following examples require you install the cogent3-h5seqs plugin. This project provides alternative storage for both unaligned sequences and for alignments.
$ pip install cogent3-h5seqs
Selecting an alternate storage backend
Specify the storage using the storage_backend argument.
from cogent3 import load_aligned_seqsaln = load_aligned_seqs("data/long_testseqs.fasta", moltype="dna", storage_backend="h5seqs_aligned")aln