Sequence Collections and Alignments¶
For loading collections of unaligned or aligned sequences see Loading an alignment from a file or url.
What’s the difference between Alignment
and ArrayAlignment
?¶
The Alignment
class can be annotated, meaning you can add annotations to an Alignment or it’s member sequences and you can slice the alignment via those objects. This capability is achieved, under the hood, by having the individual sequences represent gaps as a “span”, rather than explicitly as a “-” character in the sequence itself. This representation is also efficient for very long sequences.
The ArrayAlignment
class cannot be annotated. The class represents its sequences as a numpy.ndarray
instance. Thus, the gaps are included as a state in the array. This class is better at handling a lot of sequences and should typically be faster. This is the default class returned by the load_aligned_seqs
and make_aligned_seqs
functions. (See Loading an alignment from a file or url for details.)
You can change alignment types using the to_type()
method.
Basic Collection objects¶
Constructing a SequenceCollection
or Alignment
object from strings¶
Constructing a ArrayAlignment
using make_aligned_seqs
¶
Converting a SequenceCollection
to FASTA format¶
Adding new sequences to an existing collection or alignment¶
New sequences can be either appended or inserted using the add_seqs
method. More than one sequence can be added at the same time. Note that add_seqs
does not modify the existing collection/alignment, it creates a new one.
Appending the sequences¶
add_seqs
without additional parameters will append the sequences to the end of the collection/alignment.
Note
The order is not preserved if you use to_fasta
method, which sorts sequences by name.
Inserting the sequences¶
Sequences can be inserted into an alignment at the specified position using either the before_name
or after_name
arguments.
Inserting sequence(s) based on their alignment to a reference sequence¶
Already aligned sequences can be added to an existing Alignment
object and aligned at the same time using the add_from_ref_aln
method. The alignment is performed based on their alignment to a reference sequence (which must be present in both alignments). The method assumes the first sequence in ref_aln.names[0]
is the reference.
add_from_ref_aln
has the same arguments as add_seqs
so before_name
and after_name
can be used to insert the new sequences at the desired position.
Note
This method does not work with the ArrayAlignment
class.
Removing all columns with gaps in a named sequence¶
The elements of a collection or alignment¶
Accessing individual sequences from a collection or alignment by name¶
Using the get_seq
method allows for extracting an unaligned sequence from a collection or alignment by name.
Alternatively, if you want to extract the aligned (i.e., gapped) sequence from an alignment, you can use get_gapped_seq
.
To see the names of the sequences in a sequence collection, you can use either the Names
attribute or get_seq_names
method.
Slice the sequences from an alignment like a list¶
The usual approach is to access a SequenceCollection
or Alignment
object as a dictionary, obtaining the individual sequences using the titles as “keys” (above). However, one can also iterate through the collection like a list.
Getting a subset of sequences from the alignment¶
Note, if you set array_align=False
, then the subset contain references to the original sequences, not copies.
Alignments¶
Creating an Alignment
object from a SequenceCollection
¶
Convert alignment to DNA, RNA or PROTEIN moltypes¶
This is useful if you’ve loaded a sequence alignment without specifying the moltype and later need to convert it.
To RNA
To PROTEIN
Handling gaps¶
Remove all gaps from an alignment in FASTA format¶
This necessarily returns a SequenceCollection
.
Writing sequences to file¶
Both collection and alignment objects have a write
method. The output format is inferred from the filename suffix,
or by the format
argument.
Converting an alignment to FASTA format¶
Converting an alignment into Phylip format¶
Converting an alignment to a list of strings¶
Slicing an alignment¶
By rows (sequences)¶
An Alignment
can be sliced
but a SequenceCollection
cannot be sliced
Getting a single column from an alignment¶
Getting a region of contiguous columns¶
Iterating over alignment positions¶
Getting codon 3rd positions from Alignment
¶
We’ll do this by specifying the position indices of interest, creating a sequence Feature
and using that to extract the positions.
Getting codon 3rd positions from ArrayAlignment
¶
We can use more conventional slice notation in this instance. Note, because Python counts from 0, the 3rd position starts at index 2.
Filtering positions¶
Trim terminal stop codons¶
For evolutionary analyses that use codon models we need to exclude terminating stop codons. For the case where the sequences are all of length divisible by 3.
If the alignment contains sequences not divisible by 3, use the allow_partial
argument.
Eliminating columns with non-nucleotide characters¶
We sometimes want to eliminate ambiguous or gap data from our alignments. We show how to exclude alignment columns by the characters they contain. In the first instance we do this just for single nucleotide columns, then for trinucleotides (equivalent for handling codons). Both are done using the no_degenerates
method.
We apply to nucleotides,
Applying the same filter to trinucleotides (specified by setting motif_length=3
).
Getting all variable positions from an alignment¶
Getting all constant positions from an alignment¶
Getting all variable codons from an alignment¶
This is done using the filtered
method using the motif_length
argument. We demonstrate this first for the ArrayAlignment
.
Then for the standard Alignment
by first converting the ArrayAlignment
.
Filtering sequences¶
Extracting sequences by sequence identifier into a new alignment object¶
You can use take_seqs
to extract some sequences by sequence identifier from an alignment to a new alignment object:
Alternatively, you can extract only the sequences which are not specified by passing negate=True
:
Extracting sequences using an arbitrary function into a new alignment object¶
You can use take_seqs_if
to extract sequences into a new alignment object based on whether an arbitrary function applied to the sequence evaluates to True. For example, to extract sequences which don’t contain any N bases you could do the following:
You can additionally get the sequences where the provided function evaluates to False:
Computing alignment statistics¶
Getting motif counts¶
We state the motif length we want and whether to allow gap or ambiguous characters. The latter only has meaning for IPUAC character sets (the DNA, RNA or PROTEIN moltypes). We illustrate this for the DNA moltype with motif lengths of 1 and 3.
Note
Only the observed motifs are returned, rather than all defined by the alphabet.
Computing motif probabilities from an alignment¶
The method get_motif_probs
of Alignment
objects returns the probabilities for all motifs of a given length. For individual nucleotides:
For dinucleotides or longer, we need to pass in an Alphabet
with the appropriate word length. Here is an example with trinucleotides:
The same holds for other arbitrary alphabets, as long as they match the alignment MolType
.
Some calculations in cogent3
require all non-zero values in the motif probabilities, in which case we use a pseudo-count. We illustrate that here with a simple example where T is missing. Without the pseudo-count, the frequency of T is 0.0, with the pseudo-count defined as 1e-6 then the frequency of T will be slightly less than 1e-6.
It is important to notice that motif probabilities are computed by treating sequences as non-overlapping tuples. Below is a very simple pair of identical sequences where there are clearly 2 ‘AA’ dinucleotides per sequence but only the first one is ‘in-frame’ (frame width = 2).
We then create a dinucleotide Alphabet
object and use this to get dinucleotide probabilities. These frequencies are determined by breaking each aligned sequence up into non-overlapping dinucleotides and then doing a count. The expected value for the ‘AA’ dinucleotide in this case will be 2/8 = 0.25.
What about counting the total incidence of dinucleotides including those not in-frame? A naive application of the Python string object’s count method will not work as desired either because it “returns the number of non-overlapping occurrences”.
To count all occurrences of a given dinucleotide in a DNA sequence, one could use a standard Python approach such as list comprehension:
Working with alignment gaps¶
Filtering extracted columns for the gap character¶
Calculating the gap fraction¶
Extracting maps of aligned to unaligned positions (i.e., gap maps)¶
It’s often important to know how an alignment position relates to a position in one or more of the sequences in the alignment. The gap_maps
method of the individual sequences is useful for this. To get a map of sequence to alignment positions for a specific sequence in your alignment, do the following:
It’s now possible to look up positions in the seq1
, and find out what they map to in the alignment:
This tells us that in position 3 in seq1
corresponds to position 3 in aln
, and that position 8 in seq1
corresponds to position 9 in aln
.
Notice that we grabbed the first result from the call to gap_maps
. This is the sequence position to alignment position map. The second value returned is the alignment position to sequence position map, so if you want to find out what sequence positions the alignment positions correspond to (opposed to what alignment positions the sequence positions correspond to) for a given sequence, you would take the following steps:
If an alignment position is a gap, and therefore has no corresponding sequence position, you’ll get a KeyError
.
Note
The first position in alignments and sequences is always numbered position 0.
Filtering alignments based on gaps¶
Note
An alternate, computationally faster, approach to removing gaps is to use the filtered
method as discussed in Filtering positions.
The omit_gap_runs
method can be applied to remove long stretches of gaps in an alignment. In the following example, we remove sequences that have more than two adjacent gaps anywhere in the aligned sequence.
If instead, we just wanted to remove positions from the alignment which are gaps in more than a certain percentage of the sequences, we could use the omit_gap_pos
function. For example:
If you wanted to remove sequences which contain more than a certain percent gap characters, you could use the omit_gap_seqs
method. This is commonly applied to filter partial sequences from an alignment.
Note that following this call to omit_gap_seqs
, the 4th column of filtered_aln
is 100% gaps. This is generally not desirable, so a call to omit_gap_seqs
is frequently followed with a call to omit_gap_pos
with no parameters – this defaults to removing positions which are all gaps: