\chapter{Sequence alignments}
\label{chapter:align}

Sequence alignments are a collection of two or more sequences that have been aligned to each other -- usually with the insertion of gaps, and the addition of leading or trailing gaps -- such that all the sequence strings are the same length.

Alignments may extend over the full length of each sequence, or may be limited to a subsection of each sequence. In Biopython, all sequence alignments are represented by an \verb|Alignment| object, described in section~\ref{sec:alignmentobject}. \verb|Alignment| objects can be obtained by parsing the output of alignment software such as Clustal or BLAT (described in section~\ref{sec:alignmentparsers}. or by using Biopython's pairwise sequence aligner, which can align two sequences to each other (described in Chapter~\ref{chapter:pairwise}).

See Chapter~\ref{chapter:msa} for a description of the older \verb|MultipleSeqAlignment| class and the parsers in \verb|Bio.AlignIO| that parse the output of sequence alignment software, generating \verb|MultipleSeqAlignment| objects.

\section{Alignment objects}
\label{sec:alignmentobject}

The \verb|Alignment| class is defined in \verb|Bio.Align|. Usually you would get an \verb|Alignment| object by parsing the output of alignment programs (section~\ref{sec:alignmentparsers}) or by running Biopython's pairwise aligner (Chapter~\ref{chapter:pairwise}). For the benefit of this section, however, we will create an \verb|Alignment| object from scratch.

\subsection{Creating an Alignment object from sequences and coordinates}
\label{subsec:align_sequences_coordinates}

Suppose you have three sequences:
%doctest ../Tests/Blat lib:numpy
\begin{minted}{pycon}
>>> seqA = "CCGGTTTTT"
>>> seqB = "AGTTTAA"
>>> seqC = "AGGTTT"
>>> sequences = [seqA, seqB, seqC]
\end{minted}
To create an \verb|Alignment| object, we also need the coordinates that define how the sequences are aligned to each other. We use a NumPy array for that:
%cont-doctest
\begin{minted}{pycon}
>>> import numpy as np
>>> coordinates = np.array([[1, 3, 4, 7, 9], [0, 2, 2, 5, 5], [0, 2, 3, 6, 6]])
\end{minted}
These coordinates define the alignment for the following sequence segments:
\begin{itemize}
\item \verb|SeqA[1:3]|, \verb|SeqB[0:2]|, and \verb|SeqC[0:2]| are aligned to each other;
\item \verb|SeqA[3:4]| and \verb|SeqC[2:3]| are aligned to each other, with a gap of one nucleotide in \verb|seqB|;
\item \verb|SeqA[4:7]|, \verb|SeqB[2:5]|, and \verb|SeqC[3:6]| are aligned to each other;
\item \verb|SeqA[7:9]| is not aligned to \verb|seqB| or \verb|seqC|.
\end{itemize}
Note that the alignment does not include the first nucleotide of \verb|seqA| and last two nucleotides of \verb|seqB|.

Now we can create the \verb|Alignment| object:
%cont-doctest
\begin{minted}{pycon}
>>> from Bio.Align import Alignment
>>> alignment = Alignment(sequences, coordinates)
>>> alignment  # doctest: +ELLIPSIS
<Alignment object (3 rows x 8 columns) at ...>
\end{minted}
The alignment object has an attribute \verb|sequences| pointing to the sequences included in this alignment:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.sequences
['CCGGTTTTT', 'AGTTTAA', 'AGGTTT']
\end{minted}
and an attribute \verb|coordinates| with the alignment coordinates:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.coordinates
array([[1, 3, 4, 7, 9],
       [0, 2, 2, 5, 5],
       [0, 2, 3, 6, 6]])
\end{minted}
Print the \verb+Alignment+ object to show the alignment explicitly:
%cont-doctest
\begin{minted}{pycon}
>>> print(alignment)
                  1 CGGTTTTT 9
                  0 AG-TTT-- 5
                  0 AGGTTT-- 6
<BLANKLINE>
\end{minted}
with the starting and end coordinate for each sequence are shown to the left and right, respectively, of the alignment.

\subsection{Creating an Alignment object from aligned sequences}
\label{subsec:align_infer_coordinates}

If you start out with the aligned sequences, with dashes representing gaps, then you can calculate the coordinates using the \verb|infer_coordinates| class method. This method is primarily employed in Biopython's alignment parsers (see Section~\ref{sec:alignmentparsers}), but it may be useful for other purposes. For example, you can construct the \verb|Alignment| object from aligned sequences as follows:
%cont-doctest
\begin{minted}{pycon}
>>> aligned_sequences = ["CGGTTTTT", "AG-TTT--", "AGGTTT--"]
>>> sequences = [aligned_sequence.replace("-", "")
...              for aligned_sequence in aligned_sequences]  # fmt: skip
...
>>> sequences
['CGGTTTTT', 'AGTTT', 'AGGTTT']
>>> coordinates = Alignment.infer_coordinates(aligned_sequences)
>>> coordinates
array([[0, 2, 3, 6, 8],
       [0, 2, 2, 5, 5],
       [0, 2, 3, 6, 6]])
\end{minted}
The initial \verb|G| nucleotide of \verb|seqA| and the final \verb|CC| nucleotides of \verb|seqB| were not included in the alignment and is therefore missing here. But this is easy to fix:
%cont-doctest
\begin{minted}{pycon}
>>> sequences[0] = "C" + sequences[0]
>>> sequences[1] = sequences[1] + "AA"
>>> sequences
['CCGGTTTTT', 'AGTTTAA', 'AGGTTT']
>>> coordinates[0, :] += 1
>>> coordinates
array([[1, 3, 4, 7, 9],
       [0, 2, 2, 5, 5],
       [0, 2, 3, 6, 6]])
\end{minted}
Now we can create the \verb|Alignment| object:
%cont-doctest
\begin{minted}{pycon}
>>> alignment = Alignment(sequences, coordinates)
>>> print(alignment)
                  1 CGGTTTTT 9
                  0 AG-TTT-- 5
                  0 AGGTTT-- 6
<BLANKLINE>
\end{minted}
which identical to the \verb|Alignment| object created above in section~\ref{subsec:align_sequences_coordinates}.

By default, the \verb|coordinates| argument to the \verb|Alignment| initializer is \verb|None|, which assumes that there are no gaps in the alignment. All sequences in an ungapped alignment must have the same length. If the \verb|coordinates| argument is \verb|None|, then the initializer will fill in the \verb|coordinates| attribute of the \verb|Alignment| object for you:
%cont-doctest
\begin{minted}{pycon}
>>> ungapped_alignment = Alignment(["ACGTACGT", "AAGTACGT", "ACGTACCT"])
>>> ungapped_alignment  # doctest: +ELLIPSIS
<Alignment object (3 rows x 8 columns) at ...>
>>> ungapped_alignment.coordinates
array([[0, 8],
       [0, 8],
       [0, 8]])
>>> print(ungapped_alignment)
                  0 ACGTACGT 8
                  0 AAGTACGT 8
                  0 ACGTACCT 8
<BLANKLINE>
\end{minted}

\subsection{Common alignment attributes}
\label{subsec:align_common_attributes}

The following attributes are commonly found on \verb|Alignment| objects:
\begin{itemize}
\item \verb|sequences|: This is a list of the sequences aligned to each other. Depending on how the alignment was created, the sequences can have the following types:
\begin{itemize}
\item plain Python string;
\item \verb|Seq|;
\item \verb|MutableSeq|;
\item \verb|SeqRecord|;
\item \verb|bytes|;
\item \verb|bytearray|;
\item NumPy array with data type \verb|numpy.int32|;
\item any other object with a contiguous buffer of format \verb|"c"|, \verb|"B"|, \verb|"i"|, or \verb|"I"|;
\item lists or tuples of objects defined in the \verb|alphabet| attribute of the \verb|PairwiseAligner| object that created the alignment (see section~\ref{sec:generalized-pairwise}).
\end{itemize}
For pairwise alignments (meaning an alignment of two sequences), the properties \verb|target| and \verb|query| are aliases for \verb|sequences[0]| and \verb|sequences[1]|, respectively.
\item \verb|coordinates|: A NumPy array of integers storing the sequence indices defining how the sequences are aligned to each other;
\item \verb|score|: The alignment score, as found by the parser in the alignment file, or as calculated by the \verb|PairwiseAligner| (see section~\ref{sec:pairwise-basic});
\item \verb|annotations|: A dictionary storing most other annotations associated with the alignment;
\item \verb|column_annotations|: A dictionary storing annotations that extend along the alignment and have the same length as the alignment, such as a consensus sequence (see section~\ref{subsec:align_clustal} for an example).
\end{itemize}
An \verb|Alignment| object created by the parser in \verb|Bio.Align| may have additional attributes, depending on the alignment file format from which the alignment was read.

\section{Slicing and indexing an alignment}

Slices of the form \verb+alignment[k, i:j]+, where \verb+k+ is an integer and \verb+i+ and \verb+j+ are integers or are absent, return a string showing the aligned sequence (including gaps) for the target (if \verb+k=0+) or the query (if \verb+k=1+) that includes only the columns \verb+i+ through \verb+j+ in the printed alignment.

To illustrate this, in the following example the printed alignment has 8 columns:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment)
                  1 CGGTTTTT 9
                  0 AG-TTT-- 5
                  0 AGGTTT-- 6
<BLANKLINE>
>>> alignment.length
8
\end{minted}

To get the aligned sequence strings individually, use
%cont-doctest
\begin{minted}{pycon}
>>> alignment[0]
'CGGTTTTT'
>>> alignment[1]
'AG-TTT--'
>>> alignment[2]
'AGGTTT--'
>>> alignment[0, :]
'CGGTTTTT'
>>> alignment[1, :]
'AG-TTT--'
>>> alignment[0, 1:-1]
'GGTTTT'
>>> alignment[1, 1:-1]
'G-TTT-'
\end{minted}

Columns to be included can also be selected using an iterable over integers:
%cont-doctest
\begin{minted}{pycon}
>>> alignment[0, (1, 2, 4)]
'GGT'
>>> alignment[1, range(0, 5, 2)]
'A-T'
\end{minted}

To get the letter at position \verb+[i, j]+ of the printed alignment, use \verb|alignment[i, j]|; this will return \verb|"-"| if a gap is found at that position:
%cont-doctest
\begin{minted}{pycon}
>>> alignment[0, 2]
'G'
>>> alignment[2, 6]
'-'
\end{minted}

To get specific columns in the alignment, use
%cont-doctest
\begin{minted}{pycon}
>>> alignment[:, 0]
'CAA'
>>> alignment[:, 1]
'GGG'
>>> alignment[:, 2]
'G-G'
\end{minted}

Slices of the form \verb+alignment[i:j:k]+ return a new \verb+Alignment+ object including only sequences \verb+[i:j:k]+ of the alignment:
%cont-doctest
\begin{minted}{pycon}
>>> alignment[1:]  # doctest:+ELLIPSIS
<Alignment object (2 rows x 6 columns) at ...>
>>> print(alignment[1:])
target            0 AG-TTT 5
                  0 ||-||| 6
query             0 AGGTTT 6
<BLANKLINE>
\end{minted}

Slices of the form \verb+alignment[:, i:j]+, where \verb+i+ and \verb+j+ are integers or are absent, return a new \verb+Alignment+ object that includes only the columns \verb+i+ through \verb+j+ in the printed alignment.

Extracting the first 4 columns for the example alignment above gives:
%cont-doctest
\begin{minted}{pycon}
>>> alignment[:, :4]  # doctest:+ELLIPSIS
<Alignment object (3 rows x 4 columns) at ...>
>>> print(alignment[:, :4])
                  1 CGGT 5
                  0 AG-T 3
                  0 AGGT 4
<BLANKLINE>
\end{minted}

Similarly, extracting the last 6 columns gives:
%cont-doctest
\begin{minted}{pycon}
>>> alignment[:, -6:]  # doctest:+ELLIPSIS
<Alignment object (3 rows x 6 columns) at ...>
>>> print(alignment[:, -6:])
                  3 GTTTTT 9
                  2 -TTT-- 5
                  2 GTTT-- 6
<BLANKLINE>
\end{minted}

The column index can also be an iterable of integers:
%cont-doctest
\begin{minted}{pycon}
>>> print(alignment[:, (1, 3, 0)])
                  0 GTC 3
                  0 GTA 3
                  0 GTA 3
<BLANKLINE>
\end{minted}
Calling \verb|alignment[:, :]| returns a copy of the alignment.

\section{Getting information about the alignment}

\subsection{Alignment shape}

The number of aligned sequences is returned by \verb+len(alignment)+:
%cont-doctest
\begin{minted}{pycon}
>>> len(alignment)
3
\end{minted}
The alignment length is defined as the number of columns in the alignment as
printed. This is equal to the sum of the number of matches, number of
mismatches, and the total length of gaps in each sequence:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.length
8
\end{minted}

The \verb+shape+ property returns a tuple consisting of the length of the
alignment and the number of columns in the alignment as printed:

%cont-doctest
\begin{minted}{pycon}
>>> alignment.shape
(3, 8)
\end{minted}

\subsection{Comparing alignments}

Two alignments are equal to each other (meaning that \verb|alignment1 == alignment2| evaluates to \verb|True|) if each of the sequences in \verb|alignment1.sequences| and \verb|alignment2.sequences| are equal to each other, and \verb|alignment1.coordinates| and \verb|alignment2.coordinates| contain the same coordinates. If either of these conditions is not fulfilled, then \verb|alignment1 == alignment2| evaluates to \verb|False|. Inequality of two alignments (e.g., \verb|alignment1 < alignment2|) is established by first comparing \verb|alignment1.sequences| and \verb|alignment2.sequences|, and if they are equal, by comparing \verb|alignment1.coordinates| to \verb|alignment2.coordinates|.

\subsection{Finding the indices of aligned sequences}

For pairwise alignments, the \verb|aligned| property of an alignment returns the start and end indices of subsequences in the target and query sequence that were aligned to each other.  If the alignment between target (t) and query (q) consists of $N$ chunks, you get two tuples of length $N$:
\begin{minted}{text}
(((t_start1, t_end1), (t_start2, t_end2), ..., (t_startN, t_endN)),
 ((q_start1, q_end1), (q_start2, q_end2), ..., (q_startN, q_endN)))
\end{minted}
For example,
%cont-doctest
\begin{minted}{pycon}
>>> pairwise_alignment = alignment[:2, :]
>>> print(pairwise_alignment)
target            1 CGGTTTTT 9
                  0 .|-|||-- 8
query             0 AG-TTT-- 5
<BLANKLINE>
>>> pairwise_alignment.aligned
array([[[1, 3],
        [4, 7]],
<BLANKLINE>
       [[0, 2],
        [2, 5]]])
\end{minted}
Note that different alignments may have the same subsequences aligned to each other. In particular, this may occur if alignments differ from each other in terms of their gap placement only:
%cont-doctest
\begin{minted}{pycon}
>>> pairwise_alignment1 = Alignment(["AAACAAA", "AAAGAAA"],
...                                 np.array([[0, 3, 4, 4, 7], [0, 3, 3, 4, 7]]))  # fmt: skip
...
>>> pairwise_alignment2 = Alignment(["AAACAAA", "AAAGAAA"],
...                                 np.array([[0, 3, 3, 4, 7], [0, 3, 4, 4, 7]]))  # fmt: skip
...
>>> print(pairwise_alignment1)
target            0 AAAC-AAA 7
                  0 |||--||| 8
query             0 AAA-GAAA 7
<BLANKLINE>
>>> print(pairwise_alignment2)
target            0 AAA-CAAA 7
                  0 |||--||| 8
query             0 AAAG-AAA 7
<BLANKLINE>
>>> pairwise_alignment1.aligned
array([[[0, 3],
        [4, 7]],
<BLANKLINE>
       [[0, 3],
        [4, 7]]])
>>> pairwise_alignment2.aligned
array([[[0, 3],
        [4, 7]],
<BLANKLINE>
       [[0, 3],
        [4, 7]]])
\end{minted}

The property \verb|indices| returns a 2D NumPy array with the sequence index of each letter in the alignment, with gaps indicated by -1:
%cont-doctest
\begin{minted}{pycon}
>>> print(alignment)
                  1 CGGTTTTT 9
                  0 AG-TTT-- 5
                  0 AGGTTT-- 6
<BLANKLINE>
>>> alignment.indices
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 0,  1, -1,  2,  3,  4, -1, -1],
       [ 0,  1,  2,  3,  4,  5, -1, -1]])
\end{minted}
The property \verb|inverse_indices| returns a list of 1D NumPy arrays, one for each of the aligned sequences, with the column index in the alignment for each letter in the sequence. Letters not included in the alignment are indicated by -1:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.sequences
['CCGGTTTTT', 'AGTTTAA', 'AGGTTT']
>>> alignment.inverse_indices  # doctest: +NORMALIZE_WHITESPACE
[array([-1,  0,  1,  2,  3,  4,  5,  6,  7]),
 array([ 0,  1,  3,  4,  5, -1, -1]),
 array([0, 1, 2, 3, 4, 5])]
\end{minted}

\subsection{Counting identities, mismatches, and gaps}

The \verb|counts| method calculates the number of identities, mismatches, and gaps of a pairwise alignment.
For an alignment of more than two sequences, the number of identities, mismatches, and gaps are calculated and summed for all pairs of sequences in the alignment. The three numbers are returned as an \verb|AlignmentCounts| object, which is a \verb|namedtuple| with fields \verb|gaps|, \verb|identities|, and \verb|mismatches|. This method currently takes no arguments, but in the future will likely be modified to accept optional arguments allowing its behavior to be customized.
%cont-doctest
\begin{minted}{pycon}
>>> print(pairwise_alignment)
target            1 CGGTTTTT 9
                  0 .|-|||-- 8
query             0 AG-TTT-- 5
<BLANKLINE>
>>> pairwise_alignment.counts()
AlignmentCounts(gaps=3, identities=4, mismatches=1)
>>> print(alignment)
                  1 CGGTTTTT 9
                  0 AG-TTT-- 5
                  0 AGGTTT-- 6
<BLANKLINE>
>>> alignment.counts()
AlignmentCounts(gaps=8, identities=14, mismatches=2)
\end{minted}

\subsection{Letter frequencies}

The \verb+frequencies+ method calculates how often each letter appears in each column of the alignment:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.frequencies  # doctest: +NORMALIZE_WHITESPACE
{'C': array([1., 0., 0., 0., 0., 0., 0., 0.]),
 'G': array([0., 3., 2., 0., 0., 0., 0., 0.]),
 'T': array([0., 0., 0., 3., 3., 3., 1., 1.]),
 'A': array([2., 0., 0., 0., 0., 0., 0., 0.]),
 '-': array([0., 0., 1., 0., 0., 0., 2., 2.])}
\end{minted}

\subsection{Substitutions}

Use the \verb+substitutions+ method to find the number of substitutions between each pair of nucleotides:
%cont-doctest
\begin{minted}{pycon}
>>> m = alignment.substitutions
>>> print(m)
    A   C   G   T
A 1.0 0.0 0.0 0.0
C 2.0 0.0 0.0 0.0
G 0.0 0.0 4.0 0.0
T 0.0 0.0 0.0 9.0
<BLANKLINE>
\end{minted}

Note that the matrix is not symmetric: The counts for a row letter R and a column letter C is the number of times letter R in a sequence is replaced by letter C in a sequence appearing below it. For example, the number of \verb|C|'s that are aligned to an \verb|A| in a later sequence is
%cont-doctest
\begin{minted}{pycon}
>>> m["C", "A"]
2.0
\end{minted}
while the number of A's that are aligned to a C in a later sequence is
%cont-doctest
\begin{minted}{pycon}
>>> m["A", "C"]
0.0
\end{minted}
To get a symmetric matrix, use
%cont-doctest
\begin{minted}{pycon}
>>> m += m.transpose()
>>> m /= 2.0
>>> print(m)
    A   C   G   T
A 1.0 1.0 0.0 0.0
C 1.0 0.0 0.0 0.0
G 0.0 0.0 4.0 0.0
T 0.0 0.0 0.0 9.0
<BLANKLINE>
>>> m["A", "C"]
1.0
>>> m["C", "A"]
1.0
\end{minted}
The total number of substitutions between \verb|A|'s and \verb|T|'s in the alignment is 1.0 + 1.0 = 2.

\subsection{Alignments as arrays}

Using NumPy, you can turn the \verb+alignment+ object into an array of letters. In particular, this may be useful for fast calculations on the alignment content.
%cont-doctest
\begin{minted}{pycon}
>>> align_array = np.array(alignment)
>>> align_array.shape
(3, 8)
>>> align_array  # doctest: +NORMALIZE_WHITESPACE
array([[b'C', b'G', b'G', b'T', b'T', b'T', b'T', b'T'],
       [b'A', b'G', b'-', b'T', b'T', b'T', b'-', b'-'],
       [b'A', b'G', b'G', b'T', b'T', b'T', b'-', b'-']], dtype='|S1')
\end{minted}
By default, this will give you an array of \verb|bytes| characters (with data type \verb+dtype='|S1'+). You can create an array of Unicode (Python string) characters by using \verb+dtype='U'+:
%cont-doctest
\begin{minted}{pycon}
>>> align_array = np.array(alignment, dtype="U")
>>> align_array  # doctest: +NORMALIZE_WHITESPACE
array([['C', 'G', 'G', 'T', 'T', 'T', 'T', 'T'],
       ['A', 'G', '-', 'T', 'T', 'T', '-', '-'],
       ['A', 'G', 'G', 'T', 'T', 'T', '-', '-']], dtype='<U1')
\end{minted}
Note that the \verb+alignment+ object and the NumPy array \verb|align_array| are separate objects in memory - editing one will not update the other!

\section{Operations on an alignment}

\subsection{Sorting an alignment}

The \verb+sort+ method sorts the alignment sequences. By default, sorting is done based on the \verb+id+ attribute of each sequence if available, or the sequence contents otherwise.
%cont-doctest
\begin{minted}{pycon}
>>> print(alignment)
                  1 CGGTTTTT 9
                  0 AG-TTT-- 5
                  0 AGGTTT-- 6
<BLANKLINE>
>>> alignment.sort()
>>> print(alignment)
                  0 AGGTTT-- 6
                  0 AG-TTT-- 5
                  1 CGGTTTTT 9
<BLANKLINE>
\end{minted}
Alternatively, you can supply a \verb+key+ function to determine the sort order. For example, you can sort the sequences by increasing GC content:
%cont-doctest
\begin{minted}{pycon}
>>> from Bio.SeqUtils import gc_fraction
>>> alignment.sort(key=gc_fraction)
>>> print(alignment)  # CHEEMPIE
                  0 AG-TTT-- 5
                  0 AGGTTT-- 6
                  1 CGGTTTTT 9
<BLANKLINE>
\end{minted}
Note that the \verb+key+ function is applied to the full sequence (including the initial \verb|A| and final \verb|GG| nucleotides of \verb|seqB|), not just to the aligned part.

The \verb+reverse+ argument lets you reverse the sort order to obtain the sequences in decreasing GC content:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.sort(key=gc_fraction, reverse=True)
>>> print(alignment)
                  1 CGGTTTTT 9
                  0 AGGTTT-- 6
                  0 AG-TTT-- 5
<BLANKLINE>
\end{minted}

\subsection{Reverse-complementing the alignment}

Reverse-complementing an alignment will take the reverse complement of each sequence, and recalculate the coordinates:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.sequences
['CCGGTTTTT', 'AGGTTT', 'AGTTTAA']
>>> rc_alignment = alignment.reverse_complement()
>>> print(rc_alignment.sequences)
['AAAAACCGG', 'AAACCT', 'TTAAACT']
>>> print(rc_alignment)
                  0 AAAAACCG 8
                  0 --AAACCT 6
                  2 --AAA-CT 7
<BLANKLINE>
>>> alignment[:, :4].sequences
['CCGGTTTTT', 'AGGTTT', 'AGTTTAA']
>>> print(alignment[:, :4])
                  1 CGGT 5
                  0 AGGT 4
                  0 AG-T 3
<BLANKLINE>
>>> rc_alignment = alignment[:, :4].reverse_complement()
>>> rc_alignment[:, :4].sequences
['AAAAACCGG', 'AAACCT', 'TTAAACT']
>>> print(rc_alignment[:, :4])
                  4 ACCG 8
                  2 ACCT 6
                  4 A-CT 7
<BLANKLINE>
\end{minted}
Reverse-complementing an alignment preserves its column annotations (in reverse order), but discards all other annotations.

\subsection{Adding alignments}

Alignments can be added together to form an extended alignment if they have the same number of rows. As an example, let's first create two alignments:
%cont-doctest
\begin{minted}{pycon}
>>> from Bio.Seq import Seq
>>> from Bio.SeqRecord import SeqRecord
>>> a1 = SeqRecord(Seq("AAAAC"), id="Alpha")
>>> b1 = SeqRecord(Seq("AAAC"), id="Beta")
>>> c1 = SeqRecord(Seq("AAAAG"), id="Gamma")
>>> a2 = SeqRecord(Seq("GTT"), id="Alpha")
>>> b2 = SeqRecord(Seq("TT"), id="Beta")
>>> c2 = SeqRecord(Seq("GT"), id="Gamma")
>>> left = Alignment(
...     [a1, b1, c1], coordinates=np.array([[0, 3, 4, 5], [0, 3, 3, 4], [0, 3, 4, 5]])
... )
>>> left.annotations = {"tool": "demo", "name": "start"}
>>> left.column_annotations = {"stats": "CCCXC"}
>>> right = Alignment(
...     [a2, b2, c2], coordinates=np.array([[0, 1, 2, 3], [0, 0, 1, 2], [0, 1, 1, 2]])
... )
>>> right.annotations = {"tool": "demo", "name": "end"}
>>> right.column_annotations = {"stats": "CXC"}
\end{minted}
Now, let's look at these two alignments:
%cont-doctest
\begin{minted}{pycon}
>>> print(left)
Alpha             0 AAAAC 5
Beta              0 AAA-C 4
Gamma             0 AAAAG 5
<BLANKLINE>
>>> print(right)
Alpha             0 GTT 3
Beta              0 -TT 2
Gamma             0 G-T 2
<BLANKLINE>
\end{minted}
Adding the two alignments will combine the two alignments row-wise:
%cont-doctest
\begin{minted}{pycon}
>>> combined = left + right
>>> print(combined)
Alpha             0 AAAACGTT 8
Beta              0 AAA-C-TT 6
Gamma             0 AAAAGG-T 7
<BLANKLINE>
\end{minted}
For this to work, both alignments must have the same number of sequences
(here they both have 3 rows):
%cont-doctest
\begin{minted}{pycon}
>>> len(left)
3
>>> len(right)
3
>>> len(combined)
3
\end{minted}
The sequences are \verb|SeqRecord| objects, which can be added together. Refer
to Chapter~\ref{chapter:seq_annot} for details of how the annotation is handled.
This example is a special case in that both original alignments shared the same names, meaning when the rows are added they also get the same name.

Any common annotations are preserved, but differing annotation is lost. This is
the same behavior used in the \verb|SeqRecord| annotations and is designed to
prevent accidental propagation of inappropriate values:
%cont-doctest
\begin{minted}{pycon}
>>> combined.annotations
{'tool': 'demo'}
\end{minted}
Similarly any common per-column-annotations are combined:
%cont-doctest
\begin{minted}{pycon}
>>> combined.column_annotations
{'stats': 'CCCXCCXC'}
\end{minted}

\subsection{Mapping a pairwise sequence alignment}

Suppose you have a pairwise alignment of a transcript to a chromosome:
%cont-doctest
\begin{minted}{pycon}
>>> chromosome = "AAAAAAAACCCCCCCAAAAAAAAAAAGGGGGGAAAAAAAA"
>>> transcript = "CCCCCCCGGGGGG"
>>> sequences1 = [chromosome, transcript]
>>> coordinates1 = np.array([[8, 15, 26, 32], [0, 7, 7, 13]])
>>> alignment1 = Alignment(sequences1, coordinates1)
>>> print(alignment1)
target            8 CCCCCCCAAAAAAAAAAAGGGGGG 32
                  0 |||||||-----------|||||| 24
query             0 CCCCCCC-----------GGGGGG 13
<BLANKLINE>
\end{minted}
and a pairwise alignment between the transcript and a sequence (e.g., obtained by RNA-seq):
%cont-doctest
\begin{minted}{pycon}
>>> rnaseq = "CCCCGGGG"
>>> sequences2 = [transcript, rnaseq]
>>> coordinates2 = np.array([[3, 11], [0, 8]])
>>> alignment2 = Alignment(sequences2, coordinates2)
>>> print(alignment2)
target            3 CCCCGGGG 11
                  0 ||||||||  8
query             0 CCCCGGGG  8
<BLANKLINE>
\end{minted}
Use the \verb|map| method on \verb|alignment1|, with \verb|alignment2| as argument, to find the alignment of the RNA-sequence to the genome:
%cont-doctest
\begin{minted}{pycon}
>>> alignment3 = alignment1.map(alignment2)
>>> print(alignment3)
target           11 CCCCAAAAAAAAAAAGGGG 30
                  0 ||||-----------|||| 19
query             0 CCCC-----------GGGG  8
<BLANKLINE>
>>> alignment3.coordinates
array([[11, 15, 26, 30],
       [ 0,  4,  4,  8]])
>>> format(alignment3, "psl")
'8\t0\t0\t0\t0\t0\t1\t11\t+\tquery\t8\t0\t8\ttarget\t40\t11\t30\t2\t4,4,\t0,4,\t11,26,\n'
\end{minted}
To be able to print the sequences, in this example  we constructed \verb|alignment1| and \verb|alignment2| using sequences with a defined sequence contents.
However, mapping the alignment does not depend on the sequence contents; only the coordinates of \verb|alignment1| and \verb|alignment2| are used to construct the coordinates for \verb|alignment3|.

The map method can also be used to lift over an alignment between different genome assemblies. In this case, self is a DNA alignment between two genome assemblies, and the argument is an alignment of a transcript against one of the genome assemblies:

%cont-doctest
\begin{minted}{pycon}
>>> from Bio import Align
>>> chain = Align.read("panTro5ToPanTro6.over.chain", "chain")
>>> chain.sequences[0].id
'chr1'
>>> len(chain.sequences[0].seq)
228573443
>>> chain.sequences[1].id
'chr1'
>>> len(chain.sequences[1].seq)
224244399
>>> import numpy as np
>>> np.set_printoptions(threshold=5)  # print 5 array elements per row
>>> print(chain.coordinates)  # doctest:+ELLIPSIS
[[122250000 122250400 122250400 ... 122909818 122909819 122909835]
 [111776384 111776784 111776785 ... 112019962 112019962 112019978]]
\end{minted}
showing that the range 122250000:122909835 of chr1 on chimpanzee genome assembly panTro5 aligns to range 111776384:112019978 of chr1 of chimpanzee genome assembly panTro6. See section \ref{subsec:align_chain} for more information about the chain file format.
%cont-doctest
\begin{minted}{pycon}
>>> transcript = Align.read("est.panTro5.psl", "psl")
>>> transcript.sequences[0].id
'chr1'
>>> len(transcript.sequences[0].seq)
228573443
>>> transcript.sequences[1].id
'DC525629'
>>> len(transcript.sequences[1].seq)
407
>>> print(transcript.coordinates)
[[122835789 122835847 122840993 122841145 122907212 122907314]
 [       32        90        90       242       242       344]]
\end{minted}
This shows that nucleotide range 32:344 of expressed sequence tag DC525629
aligns to range 122835789:122907314 of chr1 of chimpanzee genome assembly
panTro5.  Note that the target sequence \verb|chain.sequences[0].seq| and the target sequence \verb|transcript.sequences[0]| have the same length:
%cont-doctest
\begin{minted}{pycon}
>>> len(chain.sequences[0].seq) == len(transcript.sequences[0].seq)
True
\end{minted}
We swap the target and query of the chain such that the query of \verb|chain| corresponds to the target of \verb|transcript|:
%cont-doctest
\begin{minted}{pycon}
>>> chain = chain[::-1]
>>> chain.sequences[0].id
'chr1'
>>> len(chain.sequences[0].seq)
224244399
>>> chain.sequences[1].id
'chr1'
>>> len(chain.sequences[1].seq)
228573443
>>> print(chain.coordinates)  # doctest:+ELLIPSIS
[[111776384 111776784 111776785 ... 112019962 112019962 112019978]
 [122250000 122250400 122250400 ... 122909818 122909819 122909835]]
>>> np.set_printoptions(threshold=1000)  # reset the print options
\end{minted}
Now we can get the coordinates of DC525629 against chimpanzee genome assembly panTro6 by calling \verb|chain.map|, with \verb|transcript| as the argument:
%cont-doctest
\begin{minted}{pycon}
>>> lifted_transcript = chain.map(transcript)
>>> lifted_transcript.sequences[0].id
'chr1'
>>> len(lifted_transcript.sequences[0].seq)
224244399
>>> lifted_transcript.sequences[1].id
'DC525629'
>>> len(lifted_transcript.sequences[1].seq)
407
>>> print(lifted_transcript.coordinates)
[[111982717 111982775 111987921 111988073 112009200 112009302]
 [       32        90        90       242       242       344]]
\end{minted}
This shows that nucleotide range 32:344 of expressed sequence tag DC525629 aligns to range 111982717:112009302 of chr1 of chimpanzee genome assembly panTro6. Note that the genome span of DC525629 on chimpanzee genome assembly panTro5 is 122907314 - 122835789 = 71525 bp, while on panTro6 the genome span is 112009302 - 111982717 = 26585 bp.

\subsection{Mapping a multiple sequence alignment}

Consider a multiple alignment of genomic sequences of chimpanzee, human, macaque, marmoset, mouse, and rat:
%cont-doctest
\begin{minted}{pycon}
>>> from Bio import Align
>>> path = "panTro5.maf"
>>> genome_alignment = Align.read(path, "maf")
>>> for record in genome_alignment.sequences:
...     print(record.id, len(record.seq))
...
panTro5.chr1 228573443
hg19.chr1 249250621
rheMac8.chr1 225584828
calJac3.chr18 47448759
mm10.chr3 160039680
rn6.chr2 266435125
>>> genome_alignment.coordinates
array([[133922962, 133922962, 133922970, 133922970, 133922972, 133922972,
        133922995, 133922998, 133923010],
       [155784573, 155784573, 155784581, 155784581, 155784583, 155784583,
        155784606, 155784609, 155784621],
       [130383910, 130383910, 130383918, 130383918, 130383920, 130383920,
        130383943, 130383946, 130383958],
       [  9790455,   9790455,   9790463,   9790463,   9790465,   9790465,
          9790488,   9790491,   9790503],
       [ 88858039,  88858036,  88858028,  88858026,  88858024,  88858020,
         88857997,  88857997,  88857985],
       [188162970, 188162967, 188162959, 188162959, 188162957, 188162953,
        188162930, 188162930, 188162918]])
>>> print(genome_alignment)
panTro5.c 133922962 ---ACTAGTTA--CA----GTAACAGAAAATAAAATTTAAATAGAAACTTAAAggcc
hg19.chr1 155784573 ---ACTAGTTA--CA----GTAACAGAAAATAAAATTTAAATAGAAACTTAAAggcc
rheMac8.c 130383910 ---ACTAGTTA--CA----GTAACAGAAAATAAAATTTAAATAGAAACTTAAAggcc
calJac3.c   9790455 ---ACTAGTTA--CA----GTAACAGAAAATAAAATTTAAATAGAAGCTTAAAggct
mm10.chr3  88858039 TATAATAATTGTATATGTCACAGAAAAAAATGAATTTTCAAT---GACTTAATAGCC
rn6.chr2  188162970 TACAATAATTG--TATGTCATAGAAAAAAATGAATTTTCAAT---AACTTAATAGCC
<BLANKLINE>
panTro5.c 133923010
hg19.chr1 155784621
rheMac8.c 130383958
calJac3.c   9790503
mm10.chr3  88857985
rn6.chr2  188162918
<BLANKLINE>
\end{minted}
Suppose we want to replace the older versions of the genome assemblies (\verb+panTro5+, \verb+hg19+, \verb+rheMac8+, \verb+calJac3+, \verb+mm10+, and \verb+rn6+) by their current versions (\verb+panTro6+, \verb+hg38+, \verb+rheMac10+, \verb+calJac4+, \verb+mm39+, and \verb+rn7+). To do so, we need the pairwise alignment between the old and the new assembly version for each species. These are provided by UCSC as chain files, typically used for UCSC's \verb+liftOver+ tool. The \verb+.chain+ files in the \verb+Tests/Align+ subdirectory in the Biopython source distribution were extracted from UCSC's \verb+.chain+ files to only include the relevant genomic region. For example, to lift over \verb+panTro5+ to \verb+panTro6+, we use the file \verb+panTro5ToPanTro6.chain+ with the following contents:
\begin{minted}{text}
chain 1198066 chr1 228573443 + 133919957 133932620 chr1 224244399 + 130607995 130620657 1
4990	0	2
1362	3	0
6308

\end{minted}
To lift over the genome assembly for each species, we read in the corresponding \verb+.chain+ file:
%cont-doctest
\begin{minted}{pycon}
>>> paths = [
...     "panTro5ToPanTro6.chain",
...     "hg19ToHg38.chain",
...     "rheMac8ToRheMac10.chain",
...     "calJac3ToCalJac4.chain",
...     "mm10ToMm39.chain",
...     "rn6ToRn7.chain",
... ]
>>> liftover_alignments = [Align.read(path, "chain") for path in paths]
>>> for liftover_alignment in liftover_alignments:
...     print(liftover_alignment.target.id, liftover_alignment.coordinates[0, :])
...
chr1 [133919957 133924947 133924947 133926309 133926312 133932620]
chr1 [155184381 156354347 156354348 157128497 157128497 157137496]
chr1 [130382477 130383872 130383872 130384222 130384222 130388520]
chr18 [9786631 9787941 9788508 9788508 9795062 9795065 9795737]
chr3 [66807541 74196805 74196831 94707528 94707528 94708176 94708178 94708718]
chr2 [188111581 188158351 188158351 188171225 188171225 188228261 188228261
 188236997]
\end{minted}
Note that the order of species is the same in \verb+liftover_alignments+ and \verb+genome_alignment.sequences+. Now we can lift over the multiple sequence alignment to the new genome assembly versions:
%cont-doctest
\begin{minted}{pycon}
>>> genome_alignment = genome_alignment.mapall(liftover_alignments)
>>> for record in genome_alignment.sequences:
...     print(record.id, len(record.seq))
...
chr1 224244399
chr1 248956422
chr1 223616942
chr18 47031477
chr3 159745316
chr2 249053267
>>> genome_alignment.coordinates
array([[130611000, 130611000, 130611008, 130611008, 130611010, 130611010,
        130611033, 130611036, 130611048],
       [155814782, 155814782, 155814790, 155814790, 155814792, 155814792,
        155814815, 155814818, 155814830],
       [ 95186253,  95186253,  95186245,  95186245,  95186243,  95186243,
         95186220,  95186217,  95186205],
       [  9758318,   9758318,   9758326,   9758326,   9758328,   9758328,
          9758351,   9758354,   9758366],
       [ 88765346,  88765343,  88765335,  88765333,  88765331,  88765327,
         88765304,  88765304,  88765292],
       [174256702, 174256699, 174256691, 174256691, 174256689, 174256685,
        174256662, 174256662, 174256650]])
\end{minted}
As the \verb+.chain+ files do not include the sequence contents, we cannot print the sequence alignment directly. Instead, we read in the genomic sequence separately (as a \verb+.2bit+ file, as it allows lazy loading; see section \ref{sec:SeqIO_directionaries}) for each species:
% This is not included in the doctest as the 2bit files are large. The unit test
% uses Fasta files with the relevant genomic regions only, but this gets a bit
% too complicated for inclusion in the documentation.
\begin{minted}{pycon}
>>> from Bio import SeqIO
>>> names = ("panTro6", "hg38", "rheMac10", "calJac4", "mm39", "rn7")
>>> for i, name in enumerate(names):
...     filename = f"{name}.2bit"
...     genome = SeqIO.parse(filename, "twobit")
...     chromosome = genome_alignment.sequences[i].id
...     assert len(genome_alignment.sequences[i]) == len(genome[chromosome])
...     genome_alignment.sequences[i] = genome[chromosome]
...     genome_alignment.sequences[i].id = f"{name}.{chromosome}"
...
>>> print(genome_alignment)
panTro6.c 130611000 ---ACTAGTTA--CA----GTAACAGAAAATAAAATTTAAATAGAAACTTAAAggcc
hg38.chr1 155814782 ---ACTAGTTA--CA----GTAACAGAAAATAAAATTTAAATAGAAACTTAAAggcc
rheMac10.  95186253 ---ACTAGTTA--CA----GTAACAGAAAATAAAATTTAAATAGAAACTTAAAggcc
calJac4.c   9758318 ---ACTAGTTA--CA----GTAACAGAaaataaaatttaaatagaagcttaaaggct
mm39.chr3  88765346 TATAATAATTGTATATGTCACAGAAAAAAATGAATTTTCAAT---GACTTAATAGCC
rn7.chr2  174256702 TACAATAATTG--TATGTCATAGAAAAAAATGAATTTTCAAT---AACTTAATAGCC
<BLANKLINE>
panTro6.c 130611048
hg38.chr1 155814830
rheMac10.  95186205
calJac4.c   9758366
mm39.chr3  88765292
rn7.chr2  174256650
<BLANKLINE>
\end{minted}
The \verb+mapall+ method can also be used to create a multiple alignment of codon sequences from a multiple sequence alignment of the corresponding amino acid sequences (see Section \ref{sec:msa_codons} for details).

\section{The Alignments class}
\label{sec:alignments}

The \verb|Alignments| (plural) class inherits from \verb|AlignmentsAbstractBaseClass| and from \verb|list|, and can be used as a list to store \verb|Alignment| objects. The behavior of \verb|Alignments| objects is different from that of \verb|list| objects in three important ways:
\begin{itemize}
\item An \verb|Alignments| object is its own iterator, whereas calling \verb|iter| on a list object creates a new iterator each time. An \verb|Alignments| object iterator will therefore behave the same as an iterator returned by \verb|Bio.Align.parse| (see section~\ref{subsec:align_reading}) or an iterator returned by the pairwise aligner (see Section~\ref{chapter:pairwise}).
%cont-doctest
\begin{minted}{pycon}
>>> from Bio.Align import Alignments

>>> alignment_list = [alignment1, alignment2, alignment3]
>>> for item in alignment_list:
...     print(repr(item))  # doctest: +ELLIPSIS
...
<Alignment object (2 rows x 24 columns) at ...>
<Alignment object (2 rows x 8 columns) at ...>
<Alignment object (2 rows x 19 columns) at ...>

>>> for item in alignment_list:
...     print(repr(item))  # doctest: +ELLIPSIS
...
<Alignment object (2 rows x 24 columns) at ...>
<Alignment object (2 rows x 8 columns) at ...>
<Alignment object (2 rows x 19 columns) at ...>

>>> alignments = Alignments([alignment1, alignment2, alignment3])
>>> for item in alignments:
...     print(repr(item))  # doctest: +ELLIPSIS
...
<Alignment object (2 rows x 24 columns) at ...>
<Alignment object (2 rows x 8 columns) at ...>
<Alignment object (2 rows x 19 columns) at ...>

>>> for item in alignments:
...     print(repr(item))  # doctest: +ELLIPSIS
...
\end{minted}
The last loop does not print anything because the iterator is already exhausted.
\item The \verb|Alignments| class defines a \verb|rewind| method that resets the iterator to its first item, allowing us to loop over it again:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.rewind()
>>> for item in alignments:
...     print(repr(item))  # doctest: +ELLIPSIS
...
<Alignment object (2 rows x 24 columns) at ...>
<Alignment object (2 rows x 8 columns) at ...>
<Alignment object (2 rows x 19 columns) at ...>
\end{minted}
\item Metadata can be stored as attributes on an \verb|Alignments| object, whereas a plain \verb|list| does not accept attributes:
%cont-doctest
\begin{minted}{pycon}
>>> alignment_list.score = 100  # doctest: +ELLIPSIS
Traceback (most recent call last):
 ...
AttributeError: 'list' object has no attribute 'score'...
>>> alignments.score = 100
>>> alignments.score
100
\end{minted}
\end{itemize}


\section{Reading and writing alignments}
\label{sec:alignmentparsers}

Output from sequence alignment software such as Clustal can be parsed into \verb|Alignment| objects by the \verb|Bio.Align.read| and \verb|Bio.Align.parse| functions. Their usage is analogous to the \verb|read| and \verb|parse| functions in \verb|Bio.SeqIO| (see Section~\ref{sec:Bio.SeqIO-input}): The \verb|read| function is used to read an output file containing a single alignment and returns an \verb|Alignment| object, while the \verb|parse| function returns an iterator to iterate over alignments stored in an output file containing one or more alignments. Section \ref{sec:alignformats} describes  the alignment formats that can be parsed in \verb|Bio.Align|.  \verb|Bio.Align| also provides a \verb|write| function that can write alignments in most of these formats.

\subsection{Reading alignments}
\label{subsec:align_reading}

The alignments iterator returned by \verb|Bio.Align.parse| inherits from the \verb|AlignmentsAbstractBaseClass| base class. This class defines a \verb|rewind| method that resets the iterator to let it loop over the alignments from the beginning. You can also call \verb|len| on the alignments to obtain the number of alignments. Depending on the file format, the number of alignments may be explicitly stored in the file (for example in the case of bigBed, bigPsl, and bigMaf files), or otherwise the number of alignments is counted by looping over them once (and returning the iterator to its original position). If the file is large, it may therefore take a considerable amount of time for \verb|len| to return. As the number of alignments is cached, subsequent calls to \verb|len| will return quickly.

Depending on the file format, the alignments object returned by \verb|Bio.Align.parse| may contain attributes that store metadata found in the file, such as the version number of the software that was used to create the alignments. The specific attributes stored for each file format are described in Section~\ref{sec:alignformats}.

\subsection{Writing alignments}
\label{subsec:align_writing}

To write alignments to a file, use
\begin{minted}{pycon}
>>> from Bio import Align
>>> target = "myfile.txt"
>>> Align.write(alignments, target, "clustal")
\end{minted}
where \verb|alignments| is either a single alignment or a list of alignments, \verb|target| is a file name or an open file-like object, and \verb|"clustal"| is the file format to be used. As some file formats allow or require metadata to be stored with the alignments, you may want to use the \verb|Alignments| (plural) class instead of a plain list of alignments (see Section~\ref{sec:alignments}), alloing you to store a metadata dictionary as an attribute on the \verb|alignments| object:
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.Alignments(alignments)
>>> metadata = {"Program": "Biopython", "Version": "1.81"}
>>> alignments.metadata = metadata
>>> target = "myfile.txt"
>>> Align.write(alignments, target, "clustal")
\end{minted}

\subsection{Printing alignments}
\label{subsec:align_printing}

For text (non-binary) formats, you can call Python's built-in \verb|format| function on an alignment to get a string showing the alignment in the requested format, or use \verb|Alignment| objects in formatted (f-) strings. If called without an argument, the \verb|format| function returns the string representation of the alignment:
%cont-doctest
\begin{minted}{pycon}
>>> str(alignment)
'                  1 CGGTTTTT 9\n                  0 AGGTTT-- 6\n                  0 AG-TTT-- 5\n'
>>> format(alignment)
'                  1 CGGTTTTT 9\n                  0 AGGTTT-- 6\n                  0 AG-TTT-- 5\n'
>>> print(format(alignment))
                  1 CGGTTTTT 9
                  0 AGGTTT-- 6
                  0 AG-TTT-- 5
<BLANKLINE>
\end{minted}
By specifying one of the formats shown in Section~\ref{sec:alignformats}, \verb+format+ will create a string showing the alignment in the requested format:
%cont-doctest
\begin{minted}{pycon}
>>> format(alignment, "clustal")
'sequence_0                          CGGTTTTT\nsequence_1                          AGGTTT--\nsequence_2                          AG-TTT--\n\n\n'
>>> print(format(alignment, "clustal"))
sequence_0                          CGGTTTTT
sequence_1                          AGGTTT--
sequence_2                          AG-TTT--
<BLANKLINE>
<BLANKLINE>
<BLANKLINE>
>>> print(f"*** this is the alignment in Clustal format: ***\n{alignment:clustal}\n***")
*** this is the alignment in Clustal format: ***
sequence_0                          CGGTTTTT
sequence_1                          AGGTTT--
sequence_2                          AG-TTT--
<BLANKLINE>
<BLANKLINE>
<BLANKLINE>
***
>>> format(alignment, "maf")
'a\ns sequence_0 1 8 + 9 CGGTTTTT\ns sequence_1 0 6 + 6 AGGTTT--\ns sequence_2 0 5 + 7 AG-TTT--\n\n'
>>> print(format(alignment, "maf"))
a
s sequence_0 1 8 + 9 CGGTTTTT
s sequence_1 0 6 + 6 AGGTTT--
s sequence_2 0 5 + 7 AG-TTT--
<BLANKLINE>
<BLANKLINE>
\end{minted}

As optional keyword arguments cannot be used with Python's built-in \verb|format| function or with formatted strings, the \verb|Alignment| class has a \verb|format| method with optional arguments to customize the alignment format, as described in the subsections below. For example, we can print the alignment in BED format (see section~\ref{subsec:align_bed}) with a specific number of columns:
%cont-doctest
\begin{minted}{pycon}
>>> print(pairwise_alignment)
target            1 CGGTTTTT 9
                  0 .|-|||-- 8
query             0 AG-TTT-- 5
<BLANKLINE>
>>> print(format(pairwise_alignment, "bed"))  # doctest: +NORMALIZE_WHITESPACE
target	1	7	query	0	+	1	7	0	2	2,3,	0,3,
<BLANKLINE>
>>> print(pairwise_alignment.format("bed"))  # doctest: +NORMALIZE_WHITESPACE
target	1	7	query	0	+	1	7	0	2	2,3,	0,3,
<BLANKLINE>
>>> print(pairwise_alignment.format("bed", bedN=3))  # doctest: +NORMALIZE_WHITESPACE
target	1	7
<BLANKLINE>
>>> print(pairwise_alignment.format("bed", bedN=6))  # doctest: +NORMALIZE_WHITESPACE
target	1	7	query	0	+
<BLANKLINE>
\end{minted}

\section{Alignment file formats}
\label{sec:alignformats}

The table below shows the alignment formats that can be parsed in Bio.Align.
The format argument \verb|fmt| used in \verb|Bio.Align| functions to specify the file format is case-insensitive. Most of these file formats can also be written by \verb|Bio.Align|, as shown in the table.

\begin{table}[!htbp]
\begin{center}
\begin{tabular}{|l|l|c|c|c|}
File format \verb+fmt+ & Description & text / binary & Supported by \verb|write| & Subsection \\
\verb|a2m| & A2M & text & yes & \ref{subsec:align_a2m} \\
\verb|bed| & Browser Extensible Data (BED) & text & yes & \ref{subsec:align_bed} \\
\verb|bigbed| & bigBed & binary & yes & \ref{subsec:align_bigbed} \\
\verb|bigmaf| & bigMaf & binary & yes & \ref{subsec:align_bigmaf} \\
\verb|bigpsl| & bigPsl & binary & yes & \ref{subsec:align_bigpsl} \\
\verb|chain| & UCSC chain file & text & yes & \ref{subsec:align_chain} \\
\verb|clustal| & ClustalW & text & yes & \ref{subsec:align_clustal} \\
\verb|emboss| & EMBOSS & text & no & \ref{subsec:align_emboss} \\
\verb|exonerate| & Exonerate & text & yes & \ref{subsec:align_exonerate} \\
\verb|fasta| & Aligned FASTA & text & yes & \ref{subsec:align_fasta} \\
\verb|hhr| & HH-suite output files & text & no & \ref{subsec:align_hhr} \\
\verb|maf| & Multiple Alignment Format (MAF) & text & yes & \ref{subsec:align_maf} \\
\verb|mauve| & Mauve eXtended Multi-FastA (xmfa) format & text & yes & \ref{subsec:align_mauve} \\
\verb|msf| & GCG Multiple Sequence Format (MSF) & text & no & \ref{subsec:align_msf} \\
\verb|nexus| & NEXUS & text & yes & \ref{subsec:align_nexus} \\
\verb|phylip| & PHYLIP output files & text & yes & \ref{subsec:align_phylip} \\
\verb|psl| & Pattern Space Layout (PSL) & text & yes & \ref{subsec:align_psl} \\
\verb|sam| & Sequence Alignment/Map (SAM) & text & yes & \ref{subsec:align_sam} \\
\verb|stockholm| & Stockholm & text & yes & \ref{subsec:align_stockholm} \\
\verb|tabular| & Tabular output from BLAST or FASTA & text & no & \ref{subsec:align_tabular} \\
\end{tabular}
\end{center}
\end{table}

\subsection{Aligned FASTA}
\label{subsec:align_fasta}

Files in the aligned FASTA format store exactly one (pairwise or multiple) sequence alignment, in which gaps in the alignment are represented by dashes (\verb|-|). Use \verb|fmt="fasta"| to read or write files in the aligned FASTA format. Note that this is different from output generated by William Pearson's FASTA alignment program (parsing such output is described in section~\ref{subsec:align_tabular} instead).

The file \verb+probcons.fa+ in Biopython's test suite stores one multiple alignment in the aligned FASTA format. The contents of this file is as follows:
\begin{minted}{text}
>plas_horvu
D-VLLGANGGVLVFEPNDFSVKAGETITFKNNAGYPHNVVFDEDAVPSG-VD-VSKISQEEYLTAPGETFSVTLTV---PGTYGFYCEPHAGAGMVGKVTV
>plas_chlre
--VKLGADSGALEFVPKTLTIKSGETVNFVNNAGFPHNIVFDEDAIPSG-VN-ADAISRDDYLNAPGETYSVKLTA---AGEYGYYCEPHQGAGMVGKIIV
>plas_anava
--VKLGSDKGLLVFEPAKLTIKPGDTVEFLNNKVPPHNVVFDAALNPAKSADLAKSLSHKQLLMSPGQSTSTTFPADAPAGEYTFYCEPHRGAGMVGKITV
>plas_proho
VQIKMGTDKYAPLYEPKALSISAGDTVEFVMNKVGPHNVIFDK--VPAG-ES-APALSNTKLRIAPGSFYSVTLGT---PGTYSFYCTPHRGAGMVGTITV
>azup_achcy
VHMLNKGKDGAMVFEPASLKVAPGDTVTFIPTDK-GHNVETIKGMIPDG-AE-A-------FKSKINENYKVTFTA---PGVYGVKCTPHYGMGMVGVVEV
\end{minted}

To read this file, use
%doctest ../Tests/Clustalw lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignment = Align.read("probcons.fa", "fasta")
>>> alignment  # doctest: +ELLIPSIS
<Alignment object (5 rows x 101 columns) at ...>
\end{minted}
We can print the alignment to see its default representation:
%cont-doctest
\begin{minted}{pycon}
>>> print(alignment)
plas_horv         0 D-VLLGANGGVLVFEPNDFSVKAGETITFKNNAGYPHNVVFDEDAVPSG-VD-VSKISQE
plas_chlr         0 --VKLGADSGALEFVPKTLTIKSGETVNFVNNAGFPHNIVFDEDAIPSG-VN-ADAISRD
plas_anav         0 --VKLGSDKGLLVFEPAKLTIKPGDTVEFLNNKVPPHNVVFDAALNPAKSADLAKSLSHK
plas_proh         0 VQIKMGTDKYAPLYEPKALSISAGDTVEFVMNKVGPHNVIFDK--VPAG-ES-APALSNT
azup_achc         0 VHMLNKGKDGAMVFEPASLKVAPGDTVTFIPTDK-GHNVETIKGMIPDG-AE-A------
<BLANKLINE>
plas_horv        57 EYLTAPGETFSVTLTV---PGTYGFYCEPHAGAGMVGKVTV 95
plas_chlr        56 DYLNAPGETYSVKLTA---AGEYGYYCEPHQGAGMVGKIIV 94
plas_anav        58 QLLMSPGQSTSTTFPADAPAGEYTFYCEPHRGAGMVGKITV 99
plas_proh        56 KLRIAPGSFYSVTLGT---PGTYSFYCTPHRGAGMVGTITV 94
azup_achc        51 -FKSKINENYKVTFTA---PGVYGVKCTPHYGMGMVGVVEV 88
<BLANKLINE>
\end{minted}
or we can print it in the aligned FASTA format:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "fasta"))
>plas_horvu
D-VLLGANGGVLVFEPNDFSVKAGETITFKNNAGYPHNVVFDEDAVPSG-VD-VSKISQEEYLTAPGETFSVTLTV---PGTYGFYCEPHAGAGMVGKVTV
>plas_chlre
--VKLGADSGALEFVPKTLTIKSGETVNFVNNAGFPHNIVFDEDAIPSG-VN-ADAISRDDYLNAPGETYSVKLTA---AGEYGYYCEPHQGAGMVGKIIV
>plas_anava
--VKLGSDKGLLVFEPAKLTIKPGDTVEFLNNKVPPHNVVFDAALNPAKSADLAKSLSHKQLLMSPGQSTSTTFPADAPAGEYTFYCEPHRGAGMVGKITV
>plas_proho
VQIKMGTDKYAPLYEPKALSISAGDTVEFVMNKVGPHNVIFDK--VPAG-ES-APALSNTKLRIAPGSFYSVTLGT---PGTYSFYCTPHRGAGMVGTITV
>azup_achcy
VHMLNKGKDGAMVFEPASLKVAPGDTVTFIPTDK-GHNVETIKGMIPDG-AE-A-------FKSKINENYKVTFTA---PGVYGVKCTPHYGMGMVGVVEV
<BLANKLINE>
\end{minted}
or any other available format, for example Clustal (see section~\ref{subsec:align_clustal}):
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "clustal"))
plas_horvu                          D-VLLGANGGVLVFEPNDFSVKAGETITFKNNAGYPHNVVFDEDAVPSG-
plas_chlre                          --VKLGADSGALEFVPKTLTIKSGETVNFVNNAGFPHNIVFDEDAIPSG-
plas_anava                          --VKLGSDKGLLVFEPAKLTIKPGDTVEFLNNKVPPHNVVFDAALNPAKS
plas_proho                          VQIKMGTDKYAPLYEPKALSISAGDTVEFVMNKVGPHNVIFDK--VPAG-
azup_achcy                          VHMLNKGKDGAMVFEPASLKVAPGDTVTFIPTDK-GHNVETIKGMIPDG-
<BLANKLINE>
plas_horvu                          VD-VSKISQEEYLTAPGETFSVTLTV---PGTYGFYCEPHAGAGMVGKVT
plas_chlre                          VN-ADAISRDDYLNAPGETYSVKLTA---AGEYGYYCEPHQGAGMVGKII
plas_anava                          ADLAKSLSHKQLLMSPGQSTSTTFPADAPAGEYTFYCEPHRGAGMVGKIT
plas_proho                          ES-APALSNTKLRIAPGSFYSVTLGT---PGTYSFYCTPHRGAGMVGTIT
azup_achcy                          AE-A-------FKSKINENYKVTFTA---PGVYGVKCTPHYGMGMVGVVE
<BLANKLINE>
plas_horvu                          V
plas_chlre                          V
plas_anava                          V
plas_proho                          V
azup_achcy                          V
<BLANKLINE>
<BLANKLINE>
<BLANKLINE>
\end{minted}
The sequences associated with the alignment are \verb|SeqRecord| objects:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.sequences
[SeqRecord(seq=Seq('DVLLGANGGVLVFEPNDFSVKAGETITFKNNAGYPHNVVFDEDAVPSGVDVSKI...VTV'), id='plas_horvu', name='<unknown name>', description='', dbxrefs=[]), SeqRecord(seq=Seq('VKLGADSGALEFVPKTLTIKSGETVNFVNNAGFPHNIVFDEDAIPSGVNADAIS...IIV'), id='plas_chlre', name='<unknown name>', description='', dbxrefs=[]), SeqRecord(seq=Seq('VKLGSDKGLLVFEPAKLTIKPGDTVEFLNNKVPPHNVVFDAALNPAKSADLAKS...ITV'), id='plas_anava', name='<unknown name>', description='', dbxrefs=[]), SeqRecord(seq=Seq('VQIKMGTDKYAPLYEPKALSISAGDTVEFVMNKVGPHNVIFDKVPAGESAPALS...ITV'), id='plas_proho', name='<unknown name>', description='', dbxrefs=[]), SeqRecord(seq=Seq('VHMLNKGKDGAMVFEPASLKVAPGDTVTFIPTDKGHNVETIKGMIPDGAEAFKS...VEV'), id='azup_achcy', name='<unknown name>', description='', dbxrefs=[])]
\end{minted}
Note that these sequences do not contain gaps ("\verb|-|" characters), as the alignment information is stored in the \verb|coordinates| attribute instead:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.coordinates
array([[ 0,  1,  1, 33, 34, 42, 44, 48, 48, 50, 50, 51, 58, 73, 73, 95],
       [ 0,  0,  0, 32, 33, 41, 43, 47, 47, 49, 49, 50, 57, 72, 72, 94],
       [ 0,  0,  0, 32, 33, 41, 43, 47, 48, 50, 51, 52, 59, 74, 77, 99],
       [ 0,  1,  2, 34, 35, 43, 43, 47, 47, 49, 49, 50, 57, 72, 72, 94],
       [ 0,  1,  2, 34, 34, 42, 44, 48, 48, 50, 50, 51, 51, 66, 66, 88]])
\end{minted}
Use \verb|Align.write| to write this alignment to a file (here, we'll use a \verb|StringIO| object instead of a file):
%cont-doctest
\begin{minted}{pycon}
>>> from io import StringIO
>>> stream = StringIO()
>>> Align.write(alignment, stream, "FASTA")
1
>>> print(stream.getvalue())
>plas_horvu
D-VLLGANGGVLVFEPNDFSVKAGETITFKNNAGYPHNVVFDEDAVPSG-VD-VSKISQEEYLTAPGETFSVTLTV---PGTYGFYCEPHAGAGMVGKVTV
>plas_chlre
--VKLGADSGALEFVPKTLTIKSGETVNFVNNAGFPHNIVFDEDAIPSG-VN-ADAISRDDYLNAPGETYSVKLTA---AGEYGYYCEPHQGAGMVGKIIV
>plas_anava
--VKLGSDKGLLVFEPAKLTIKPGDTVEFLNNKVPPHNVVFDAALNPAKSADLAKSLSHKQLLMSPGQSTSTTFPADAPAGEYTFYCEPHRGAGMVGKITV
>plas_proho
VQIKMGTDKYAPLYEPKALSISAGDTVEFVMNKVGPHNVIFDK--VPAG-ES-APALSNTKLRIAPGSFYSVTLGT---PGTYSFYCTPHRGAGMVGTITV
>azup_achcy
VHMLNKGKDGAMVFEPASLKVAPGDTVTFIPTDK-GHNVETIKGMIPDG-AE-A-------FKSKINENYKVTFTA---PGVYGVKCTPHYGMGMVGVVEV
<BLANKLINE>
\end{minted}
Note that \verb|Align.write| returns the number of alignments written (1, in this case).

\subsection{ClustalW}
\label{subsec:align_clustal}

Clustal is a set of multiple sequence alignment programs that are available both as standalone programs as as web servers. The file \verb|opuntia.aln| (available online or in the \verb|Doc/examples| subdirectory of the Biopython source code) is an output file generated by Clustal. Its first few lines are
\begin{minted}{text}
CLUSTAL 2.1 multiple sequence alignment


gi|6273285|gb|AF191659.1|AF191      TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273284|gb|AF191658.1|AF191      TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273287|gb|AF191661.1|AF191      TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273286|gb|AF191660.1|AF191      TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273290|gb|AF191664.1|AF191      TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273289|gb|AF191663.1|AF191      TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273291|gb|AF191665.1|AF191      TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
                                    ******* **** *************************************

...
\end{minted}
To parse this file, use
%doctest examples lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("opuntia.aln", "clustal")
\end{minted}
The \verb|metadata| attribute on \verb|alignments| stores the information shown in the file header:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.metadata
{'Program': 'CLUSTAL', 'Version': '2.1'}
\end{minted}
You can call \verb|next| on the \verb|alignments| to pull out the first (and only) alignment:
%cont-doctest
\begin{minted}{pycon}
>>> alignment = next(alignments)
>>> print(alignment)  # doctest: +ELLIPSIS
gi|627328         0 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAAAAAAATGAAT
gi|627328         0 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAAAAAAATGAAT
gi|627328         0 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAAAAAAATGAAT
gi|627328         0 TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAAAAAAATGAAT
gi|627329         0 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAAAAAAATGAAT
gi|627328         0 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAAAAAAATGAAT
gi|627329         0 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAAAAAAATGAAT
<BLANKLINE>
gi|627328        60 CTAAATGATATACGATTCCACTATGTAAGGTCTTTGAATCATATCATAAAAGACAATGTA
gi|627328        60 CTAAATGATATACGATTCCACTATGTAAGGTCTTTGAATCATATCATAAAAGACAATGTA
gi|627328        60 CTAAATGATATACGATTCCACTATGTAAGGTCTTTGAATCATATCATAAAAGACAATGTA
gi|627328        60 CTAAATGATATACGATTCCACTA...
\end{minted}
If you are not interested in the metadata, then it is more convenient to use the \verb|Align.read| function, as anyway each Clustal file contains only one alignment:
%cont-doctest
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignment = Align.read("opuntia.aln", "clustal")
\end{minted}
The consensus line below each alignment block in the Clustal output file contains an asterisk if the sequence is conserved at each position. This information is stored in the \verb|column_annotations| attribute of the \verb|alignment|:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.column_annotations  # doctest: +ELLIPSIS
{'clustal_consensus': '******* **** **********************************...
\end{minted}
Printing the \verb|alignment| in \verb|clustal| format will show the sequence alignment, but does not include the metadata:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "clustal"))  # doctest: +ELLIPSIS
gi|6273285|gb|AF191659.1|AF191      TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273284|gb|AF191658.1|AF191      TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273287|gb|AF191661.1|AF191      TATACATT...
\end{minted}
Writing the \verb|alignments| in \verb|clustal| format will include both the metadata and the sequence alignment:
%cont-doctest
\begin{minted}{pycon}
>>> from io import StringIO
>>> stream = StringIO()
>>> alignments.rewind()
>>> Align.write(alignments, stream, "clustal")
1
>>> print(stream.getvalue())  # doctest: +ELLIPSIS
CLUSTAL 2.1 multiple sequence alignment
<BLANKLINE>
<BLANKLINE>
gi|6273285|gb|AF191659.1|AF191      TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273284|gb|AF191658.1|AF191      TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273287|gb|AF191661.1|AF191      TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAA
gi|6273286|gb|AF191660.1|AF191      TATACATAAAAGAAG...
\end{minted}
Use an \verb|Alignments| (plural) object (see Section~\ref{sec:alignments}) if you are creating alignments by hand, and would like to include metadata information in the output.

\subsection{Stockholm}
\label{subsec:align_stockholm}

This is an example of a protein sequence alignment in the Stockholm file format used by PFAM:

\begin{minted}{text}
# STOCKHOLM 1.0
#=GF ID   7kD_DNA_binding
#=GF AC   PF02294.20
#=GF DE   7kD DNA-binding domain
#=GF AU   Mian N;0000-0003-4284-4749
#=GF AU   Bateman A;0000-0002-6982-4660
#=GF SE   Pfam-B_8148 (release 5.2)
#=GF GA   25.00 25.00;
#=GF TC   26.60 46.20;
#=GF NC   23.20 19.20;
#=GF BM   hmmbuild HMM.ann SEED.ann
#=GF SM   hmmsearch -Z 57096847 -E 1000 --cpu 4 HMM pfamseq
#=GF TP   Domain
#=GF CL   CL0049
#=GF RN   [1]
#=GF RM   3130377
#=GF RT   Microsequence analysis of DNA-binding proteins 7a, 7b, and 7e
#=GF RT   from the archaebacterium Sulfolobus acidocaldarius. 
#=GF RA   Choli T, Wittmann-Liebold B, Reinhardt R; 
#=GF RL   J Biol Chem 1988;263:7087-7093.
#=GF DR   INTERPRO; IPR003212;
#=GF DR   SCOP; 1sso; fa;
#=GF DR   SO; 0000417; polypeptide_domain;
#=GF CC   This family contains members of the hyper-thermophilic
#=GF CC   archaebacterium  7kD DNA-binding/endoribonuclease P2 family.
#=GF CC   There are five 7kD DNA-binding proteins, 7a-7e, found as
#=GF CC   monomers in the cell. Protein 7e shows the  tightest DNA-binding
#=GF CC   ability.
#=GF SQ   3
#=GS DN7_METS5/4-61   AC A4YEA2.1
#=GS DN7A_SACS2/3-61  AC P61991.2
#=GS DN7A_SACS2/3-61  DR PDB; 1SSO A; 2-60;
#=GS DN7A_SACS2/3-61  DR PDB; 1JIC A; 2-60;
#=GS DN7A_SACS2/3-61  DR PDB; 2CVR A; 2-60;
#=GS DN7A_SACS2/3-61  DR PDB; 1B4O A; 2-60;
#=GS DN7E_SULAC/3-60  AC P13125.2
DN7_METS5/4-61              KIKFKYKGQDLEVDISKVKKVWKVGKMVSFTYDD.NGKTGRGAVSEKDAPKELLNMIGK
DN7A_SACS2/3-61             TVKFKYKGEEKQVDISKIKKVWRVGKMISFTYDEGGGKTGRGAVSEKDAPKELLQMLEK
#=GR DN7A_SACS2/3-61  SS    EEEEESSSSEEEEETTTEEEEEESSSSEEEEEE-SSSSEEEEEEETTTS-CHHHHHHTT
DN7E_SULAC/3-60             KVRFKYKGEEKEVDTSKIKKVWRVGKMVSFTYDD.NGKTGRGAVSEKDAPKELMDMLAR
#=GC SS_cons                EEEEESSSSEEEEETTTEEEEEESSSSEEEEEE-SSSSEEEEEEETTTS-CHHHHHHTT
#=GC seq_cons               KVKFKYKGEEKEVDISKIKKVWRVGKMVSFTYDD.NGKTGRGAVSEKDAPKELLsMLuK
//
\end{minted}
This is the seed alignment for the 7kD\_DNA\_binding (PF02294.20) PFAM entry, downloaded from the InterPro website (\url{https://www.ebi.ac.uk/interpro/}). This version of the PFAM entry is also available in the Biopython source distribution as the file \verb+pfam2.seed.txt+ in the subdirectory \verb+Tests/Stockholm/+. We can load this file as follows:
%doctest ../Tests/Stockholm lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignment = Align.read("pfam2.seed.txt", "stockholm")
>>> alignment  # doctest: +ELLIPSIS
<Alignment object (3 rows x 59 columns) at ...>
\end{minted}

\noindent We can print out a summary of the alignment:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment)
DN7_METS5         0 KIKFKYKGQDLEVDISKVKKVWKVGKMVSFTYDD-NGKTGRGAVSEKDAPKELLNMIGK
DN7A_SACS         0 TVKFKYKGEEKQVDISKIKKVWRVGKMISFTYDEGGGKTGRGAVSEKDAPKELLQMLEK
DN7E_SULA         0 KVRFKYKGEEKEVDTSKIKKVWRVGKMVSFTYDD-NGKTGRGAVSEKDAPKELMDMLAR
<BLANKLINE>
DN7_METS5        58
DN7A_SACS        59
DN7E_SULA        58
<BLANKLINE>
\end{minted}

You could also call Python's built-in \verb|format| function on the alignment object to show it in a particular file format (see section~\ref{subsec:align_printing} for details), for example in the Stockholm format to regenerate the file:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "stockholm"))
# STOCKHOLM 1.0
#=GF ID   7kD_DNA_binding
#=GF AC   PF02294.20
#=GF DE   7kD DNA-binding domain
#=GF AU   Mian N;0000-0003-4284-4749
#=GF AU   Bateman A;0000-0002-6982-4660
#=GF SE   Pfam-B_8148 (release 5.2)
#=GF GA   25.00 25.00;
#=GF TC   26.60 46.20;
#=GF NC   23.20 19.20;
#=GF BM   hmmbuild HMM.ann SEED.ann
#=GF SM   hmmsearch -Z 57096847 -E 1000 --cpu 4 HMM pfamseq
#=GF TP   Domain
#=GF CL   CL0049
#=GF RN   [1]
#=GF RM   3130377
#=GF RT   Microsequence analysis of DNA-binding proteins 7a, 7b, and 7e from
#=GF RT   the archaebacterium Sulfolobus acidocaldarius.
#=GF RA   Choli T, Wittmann-Liebold B, Reinhardt R;
#=GF RL   J Biol Chem 1988;263:7087-7093.
#=GF DR   INTERPRO; IPR003212;
#=GF DR   SCOP; 1sso; fa;
#=GF DR   SO; 0000417; polypeptide_domain;
#=GF CC   This family contains members of the hyper-thermophilic
#=GF CC   archaebacterium  7kD DNA-binding/endoribonuclease P2 family. There
#=GF CC   are five 7kD DNA-binding proteins, 7a-7e, found as monomers in the
#=GF CC   cell. Protein 7e shows the  tightest DNA-binding ability.
#=GF SQ   3
#=GS DN7_METS5/4-61   AC A4YEA2.1
#=GS DN7A_SACS2/3-61  AC P61991.2
#=GS DN7A_SACS2/3-61  DR PDB; 1SSO A; 2-60;
#=GS DN7A_SACS2/3-61  DR PDB; 1JIC A; 2-60;
#=GS DN7A_SACS2/3-61  DR PDB; 2CVR A; 2-60;
#=GS DN7A_SACS2/3-61  DR PDB; 1B4O A; 2-60;
#=GS DN7E_SULAC/3-60  AC P13125.2
DN7_METS5/4-61                  KIKFKYKGQDLEVDISKVKKVWKVGKMVSFTYDD.NGKTGRGAVSEKDAPKELLNMIGK
DN7A_SACS2/3-61                 TVKFKYKGEEKQVDISKIKKVWRVGKMISFTYDEGGGKTGRGAVSEKDAPKELLQMLEK
#=GR DN7A_SACS2/3-61  SS        EEEEESSSSEEEEETTTEEEEEESSSSEEEEEE-SSSSEEEEEEETTTS-CHHHHHHTT
DN7E_SULAC/3-60                 KVRFKYKGEEKEVDTSKIKKVWRVGKMVSFTYDD.NGKTGRGAVSEKDAPKELMDMLAR
#=GC SS_cons                    EEEEESSSSEEEEETTTEEEEEESSSSEEEEEE-SSSSEEEEEEETTTS-CHHHHHHTT
#=GC seq_cons                   KVKFKYKGEEKEVDISKIKKVWRVGKMVSFTYDD.NGKTGRGAVSEKDAPKELLsMLuK
//
<BLANKLINE>
\end{minted}
or alternatively as aligned FASTA (see section \ref{subsec:align_fasta}):
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "fasta"))
>DN7_METS5/4-61
KIKFKYKGQDLEVDISKVKKVWKVGKMVSFTYDD-NGKTGRGAVSEKDAPKELLNMIGK
>DN7A_SACS2/3-61
TVKFKYKGEEKQVDISKIKKVWRVGKMISFTYDEGGGKTGRGAVSEKDAPKELLQMLEK
>DN7E_SULAC/3-60
KVRFKYKGEEKEVDTSKIKKVWRVGKMVSFTYDD-NGKTGRGAVSEKDAPKELMDMLAR
<BLANKLINE>
\end{minted}
or in the PHYLIP format (see section~\ref{subsec:align_phylip}):
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "phylip"))
3 59
DN7_METS5/KIKFKYKGQDLEVDISKVKKVWKVGKMVSFTYDD-NGKTGRGAVSEKDAPKELLNMIGK
DN7A_SACS2TVKFKYKGEEKQVDISKIKKVWRVGKMISFTYDEGGGKTGRGAVSEKDAPKELLQMLEK
DN7E_SULACKVRFKYKGEEKEVDTSKIKKVWRVGKMVSFTYDD-NGKTGRGAVSEKDAPKELMDMLAR
<BLANKLINE>
\end{minted}
General information of the alignment is stored under the \verb+annotations+ attribute of the \verb+Alignment+ object, for example
%cont-doctest
\begin{minted}{pycon}
>>> alignment.annotations["identifier"]
'7kD_DNA_binding'
>>> alignment.annotations["clan"]
'CL0049'
>>> alignment.annotations["database references"]
[{'reference': 'INTERPRO; IPR003212;'}, {'reference': 'SCOP; 1sso; fa;'}, {'reference': 'SO; 0000417; polypeptide_domain;'}]
\end{minted}
The individual sequences in this alignment are stored under \verb|alignment.sequences| as \verb|SeqRecord|s, including any annotations associated with each sequence record:
%cont-doctest
\begin{minted}{pycon}
>>> for record in alignment.sequences:
...     print("%s %s %s" % (record.id, record.annotations["accession"], record.dbxrefs))
...
DN7_METS5/4-61 A4YEA2.1 []
DN7A_SACS2/3-61 P61991.2 ['PDB; 1SSO A; 2-60;', 'PDB; 1JIC A; 2-60;', 'PDB; 2CVR A; 2-60;', 'PDB; 1B4O A; 2-60;']
DN7E_SULAC/3-60 P13125.2 []
\end{minted}
The secondary structure of the second sequence (\verb+DN7A_SACS2/3-61+) is stored in the \verb+letter_annotations+ attribute of the \verb+SeqRecord+:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.sequences[0].letter_annotations
{}
>>> alignment.sequences[1].letter_annotations
{'secondary structure': 'EEEEESSSSEEEEETTTEEEEEESSSSEEEEEE-SSSSEEEEEEETTTS-CHHHHHHTT'}
>>> alignment.sequences[2].letter_annotations
{}
\end{minted}
The consensus sequence and secondary structure are associated with the sequence alignment as a whole, and are therefore stored in the \verb+column_annotations+ attribute of the \verb+Alignment+ object:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.column_annotations  # doctest: +NORMALIZE_WHITESPACE
{'consensus secondary structure': 'EEEEESSSSEEEEETTTEEEEEESSSSEEEEEE-SSSSEEEEEEETTTS-CHHHHHHTT',
 'consensus sequence': 'KVKFKYKGEEKEVDISKIKKVWRVGKMVSFTYDD.NGKTGRGAVSEKDAPKELLsMLuK'}
\end{minted}

\subsection{PHYLIP output files}
\label{subsec:align_phylip}

The PHYLIP format for sequence alignments is derived from the PHYLogeny Interference Package from Joe Felsenstein. Files in the PHYLIP format start with two numbers for the number of rows and columns in the printed alignment. The sequence alignment itself can be in sequential format or in interleaved format. An example of the former is the \verb|sequential.phy| file (provided in \verb+Tests/Phylip/+ in the Biopython source distribution):
\begin{minted}{text}
 3 384
CYS1_DICDI   -----MKVIL LFVLAVFTVF VSS------- --------RG IPPEEQ---- --------SQ 
             FLEFQDKFNK KY-SHEEYLE RFEIFKSNLG KIEELNLIAI NHKADTKFGV NKFADLSSDE 
             FKNYYLNNKE AIFTDDLPVA DYLDDEFINS IPTAFDWRTR G-AVTPVKNQ GQCGSCWSFS 
             TTGNVEGQHF ISQNKLVSLS EQNLVDCDHE CMEYEGEEAC DEGCNGGLQP NAYNYIIKNG 
             GIQTESSYPY TAETGTQCNF NSANIGAKIS NFTMIP-KNE TVMAGYIVST GPLAIAADAV 
             E-WQFYIGGV F-DIPCN--P NSLDHGILIV GYSAKNTIFR KNMPYWIVKN SWGADWGEQG 
             YIYLRRGKNT CGVSNFVSTS II-- 
ALEU_HORVU   MAHARVLLLA LAVLATAAVA VASSSSFADS NPIRPVTDRA ASTLESAVLG ALGRTRHALR 
             FARFAVRYGK SYESAAEVRR RFRIFSESLE EVRSTN---- RKGLPYRLGI NRFSDMSWEE 
             FQATRL-GAA QTCSATLAGN HLMRDA--AA LPETKDWRED G-IVSPVKNQ AHCGSCWTFS 
             TTGALEAAYT QATGKNISLS EQQLVDCAGG FNNF------ --GCNGGLPS QAFEYIKYNG 
             GIDTEESYPY KGVNGV-CHY KAENAAVQVL DSVNITLNAE DELKNAVGLV RPVSVAFQVI 
             DGFRQYKSGV YTSDHCGTTP DDVNHAVLAV GYGVENGV-- ---PYWLIKN SWGADWGDNG 
             YFKMEMGKNM CAIATCASYP VVAA 
CATH_HUMAN   ------MWAT LPLLCAGAWL LGV------- -PVCGAAELS VNSLEK---- --------FH 
             FKSWMSKHRK TY-STEEYHH RLQTFASNWR KINAHN---- NGNHTFKMAL NQFSDMSFAE 
             IKHKYLWSEP QNCSAT--KS NYLRGT--GP YPPSVDWRKK GNFVSPVKNQ GACGSCWTFS 
             TTGALESAIA IATGKMLSLA EQQLVDCAQD FNNY------ --GCQGGLPS QAFEYILYNK 
             GIMGEDTYPY QGKDGY-CKF QPGKAIGFVK DVANITIYDE EAMVEAVALY NPVSFAFEVT 
             QDFMMYRTGI YSSTSCHKTP DKVNHAVLAV GYGEKNGI-- ---PYWIVKN SWGPQWGMNG 
             YFLIERGKNM CGLAACASYP IPLV
\end{minted}
In the sequential format, the complete alignment for one sequence is shown before proceeding to the next sequence. In the interleaved format, the alignments for different sequences are next to each other, for example in the file \verb|interlaced.phy| (provided in \verb+Tests/Phylip/+ in the Biopython source distribution):
\begin{minted}{text}
 3 384
CYS1_DICDI   -----MKVIL LFVLAVFTVF VSS------- --------RG IPPEEQ---- --------SQ 
ALEU_HORVU   MAHARVLLLA LAVLATAAVA VASSSSFADS NPIRPVTDRA ASTLESAVLG ALGRTRHALR 
CATH_HUMAN   ------MWAT LPLLCAGAWL LGV------- -PVCGAAELS VNSLEK---- --------FH 

             FLEFQDKFNK KY-SHEEYLE RFEIFKSNLG KIEELNLIAI NHKADTKFGV NKFADLSSDE 
             FARFAVRYGK SYESAAEVRR RFRIFSESLE EVRSTN---- RKGLPYRLGI NRFSDMSWEE 
             FKSWMSKHRK TY-STEEYHH RLQTFASNWR KINAHN---- NGNHTFKMAL NQFSDMSFAE 

             FKNYYLNNKE AIFTDDLPVA DYLDDEFINS IPTAFDWRTR G-AVTPVKNQ GQCGSCWSFS 
             FQATRL-GAA QTCSATLAGN HLMRDA--AA LPETKDWRED G-IVSPVKNQ AHCGSCWTFS 
             IKHKYLWSEP QNCSAT--KS NYLRGT--GP YPPSVDWRKK GNFVSPVKNQ GACGSCWTFS 

             TTGNVEGQHF ISQNKLVSLS EQNLVDCDHE CMEYEGEEAC DEGCNGGLQP NAYNYIIKNG 
             TTGALEAAYT QATGKNISLS EQQLVDCAGG FNNF------ --GCNGGLPS QAFEYIKYNG 
             TTGALESAIA IATGKMLSLA EQQLVDCAQD FNNY------ --GCQGGLPS QAFEYILYNK 

             GIQTESSYPY TAETGTQCNF NSANIGAKIS NFTMIP-KNE TVMAGYIVST GPLAIAADAV 
             GIDTEESYPY KGVNGV-CHY KAENAAVQVL DSVNITLNAE DELKNAVGLV RPVSVAFQVI 
             GIMGEDTYPY QGKDGY-CKF QPGKAIGFVK DVANITIYDE EAMVEAVALY NPVSFAFEVT 

             E-WQFYIGGV F-DIPCN--P NSLDHGILIV GYSAKNTIFR KNMPYWIVKN SWGADWGEQG 
             DGFRQYKSGV YTSDHCGTTP DDVNHAVLAV GYGVENGV-- ---PYWLIKN SWGADWGDNG 
             QDFMMYRTGI YSSTSCHKTP DKVNHAVLAV GYGEKNGI-- ---PYWIVKN SWGPQWGMNG 

             YIYLRRGKNT CGVSNFVSTS II-- 
             YFKMEMGKNM CAIATCASYP VVAA 
             YFLIERGKNM CGLAACASYP IPLV
\end{minted}
The parser in \verb|Bio.Align| detects from the file contents if it is in the sequential or in the interleaved format, and then parses it appropriately.
%doctest ../Tests/Phylip lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignment = Align.read("sequential.phy", "phylip")
>>> alignment  # doctest: +ELLIPSIS
<Alignment object (3 rows x 384 columns) at ...>
>>> alignment2 = Align.read("interlaced.phy", "phylip")
>>> alignment2  # doctest: +ELLIPSIS
<Alignment object (3 rows x 384 columns) at ...>
>>> alignment == alignment2
True
\end{minted}
Here, two alignments are considered to be equal if they have the same sequence contents and the same alignment coordinates.
%cont-doctest
\begin{minted}{pycon}
>>> alignment.shape
(3, 384)
>>> print(alignment)
CYS1_DICD         0 -----MKVILLFVLAVFTVFVSS---------------RGIPPEEQ------------SQ
ALEU_HORV         0 MAHARVLLLALAVLATAAVAVASSSSFADSNPIRPVTDRAASTLESAVLGALGRTRHALR
CATH_HUMA         0 ------MWATLPLLCAGAWLLGV--------PVCGAAELSVNSLEK------------FH
<BLANKLINE>
CYS1_DICD        28 FLEFQDKFNKKY-SHEEYLERFEIFKSNLGKIEELNLIAINHKADTKFGVNKFADLSSDE
ALEU_HORV        60 FARFAVRYGKSYESAAEVRRRFRIFSESLEEVRSTN----RKGLPYRLGINRFSDMSWEE
CATH_HUMA        34 FKSWMSKHRKTY-STEEYHHRLQTFASNWRKINAHN----NGNHTFKMALNQFSDMSFAE
<BLANKLINE>
CYS1_DICD        87 FKNYYLNNKEAIFTDDLPVADYLDDEFINSIPTAFDWRTRG-AVTPVKNQGQCGSCWSFS
ALEU_HORV       116 FQATRL-GAAQTCSATLAGNHLMRDA--AALPETKDWREDG-IVSPVKNQAHCGSCWTFS
CATH_HUMA        89 IKHKYLWSEPQNCSAT--KSNYLRGT--GPYPPSVDWRKKGNFVSPVKNQGACGSCWTFS
<BLANKLINE>
CYS1_DICD       146 TTGNVEGQHFISQNKLVSLSEQNLVDCDHECMEYEGEEACDEGCNGGLQPNAYNYIIKNG
ALEU_HORV       172 TTGALEAAYTQATGKNISLSEQQLVDCAGGFNNF--------GCNGGLPSQAFEYIKYNG
CATH_HUMA       145 TTGALESAIAIATGKMLSLAEQQLVDCAQDFNNY--------GCQGGLPSQAFEYILYNK
<BLANKLINE>
CYS1_DICD       206 GIQTESSYPYTAETGTQCNFNSANIGAKISNFTMIP-KNETVMAGYIVSTGPLAIAADAV
ALEU_HORV       224 GIDTEESYPYKGVNGV-CHYKAENAAVQVLDSVNITLNAEDELKNAVGLVRPVSVAFQVI
CATH_HUMA       197 GIMGEDTYPYQGKDGY-CKFQPGKAIGFVKDVANITIYDEEAMVEAVALYNPVSFAFEVT
<BLANKLINE>
CYS1_DICD       265 E-WQFYIGGVF-DIPCN--PNSLDHGILIVGYSAKNTIFRKNMPYWIVKNSWGADWGEQG
ALEU_HORV       283 DGFRQYKSGVYTSDHCGTTPDDVNHAVLAVGYGVENGV-----PYWLIKNSWGADWGDNG
CATH_HUMA       256 QDFMMYRTGIYSSTSCHKTPDKVNHAVLAVGYGEKNGI-----PYWIVKNSWGPQWGMNG
<BLANKLINE>
CYS1_DICD       321 YIYLRRGKNTCGVSNFVSTSII-- 343
ALEU_HORV       338 YFKMEMGKNMCAIATCASYPVVAA 362
CATH_HUMA       311 YFLIERGKNMCGLAACASYPIPLV 335
<BLANKLINE>
\end{minted}
When outputting the alignment in PHYLIP format, \verb|Bio.Align| writes each of the aligned sequences on one line:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "phylip"))
3 384
CYS1_DICDI-----MKVILLFVLAVFTVFVSS---------------RGIPPEEQ------------SQFLEFQDKFNKKY-SHEEYLERFEIFKSNLGKIEELNLIAINHKADTKFGVNKFADLSSDEFKNYYLNNKEAIFTDDLPVADYLDDEFINSIPTAFDWRTRG-AVTPVKNQGQCGSCWSFSTTGNVEGQHFISQNKLVSLSEQNLVDCDHECMEYEGEEACDEGCNGGLQPNAYNYIIKNGGIQTESSYPYTAETGTQCNFNSANIGAKISNFTMIP-KNETVMAGYIVSTGPLAIAADAVE-WQFYIGGVF-DIPCN--PNSLDHGILIVGYSAKNTIFRKNMPYWIVKNSWGADWGEQGYIYLRRGKNTCGVSNFVSTSII--
ALEU_HORVUMAHARVLLLALAVLATAAVAVASSSSFADSNPIRPVTDRAASTLESAVLGALGRTRHALRFARFAVRYGKSYESAAEVRRRFRIFSESLEEVRSTN----RKGLPYRLGINRFSDMSWEEFQATRL-GAAQTCSATLAGNHLMRDA--AALPETKDWREDG-IVSPVKNQAHCGSCWTFSTTGALEAAYTQATGKNISLSEQQLVDCAGGFNNF--------GCNGGLPSQAFEYIKYNGGIDTEESYPYKGVNGV-CHYKAENAAVQVLDSVNITLNAEDELKNAVGLVRPVSVAFQVIDGFRQYKSGVYTSDHCGTTPDDVNHAVLAVGYGVENGV-----PYWLIKNSWGADWGDNGYFKMEMGKNMCAIATCASYPVVAA
CATH_HUMAN------MWATLPLLCAGAWLLGV--------PVCGAAELSVNSLEK------------FHFKSWMSKHRKTY-STEEYHHRLQTFASNWRKINAHN----NGNHTFKMALNQFSDMSFAEIKHKYLWSEPQNCSAT--KSNYLRGT--GPYPPSVDWRKKGNFVSPVKNQGACGSCWTFSTTGALESAIAIATGKMLSLAEQQLVDCAQDFNNY--------GCQGGLPSQAFEYILYNKGIMGEDTYPYQGKDGY-CKFQPGKAIGFVKDVANITIYDEEAMVEAVALYNPVSFAFEVTQDFMMYRTGIYSSTSCHKTPDKVNHAVLAVGYGEKNGI-----PYWIVKNSWGPQWGMNGYFLIERGKNMCGLAACASYPIPLV
<BLANKLINE>
\end{minted}
We can write the alignment in PHYLIP format, parse the result, and confirm it is the same as the original alignment object:
%cont-doctest
\begin{minted}{pycon}
>>> from io import StringIO
>>> stream = StringIO()
>>> Align.write(alignment, stream, "phylip")
1
>>> stream.seek(0)
0
>>> alignment3 = Align.read(stream, "phylip")
>>> alignment == alignment3
True
>>> [record.id for record in alignment.sequences]
['CYS1_DICDI', 'ALEU_HORVU', 'CATH_HUMAN']
>>> [record.id for record in alignment3.sequences]
['CYS1_DICDI', 'ALEU_HORVU', 'CATH_HUMAN']
\end{minted}

\subsection{EMBOSS}
\label{subsec:align_emboss}

EMBOSS (European Molecular Biology Open Software Suite) is a set of open-source software tools for molecular biology and bioinformatics~\cite{rice2000}. It includes software such as \verb|needle| and \verb|water| for pairwise sequence alignment. This is an example of output generated by the \verb|water| program for Smith-Waterman local pairwise sequence alignment (available as \verb|water.txt| in the \verb|Tests/Emboss| directory of the Biopython distribution):
\begin{minted}{text}
########################################
# Program:  water
# Rundate:  Wed Jan 16 17:23:19 2002
# Report_file: stdout
########################################
#=======================================
#
# Aligned_sequences: 2
# 1: IXI_234
# 2: IXI_235
# Matrix: EBLOSUM62
# Gap_penalty: 10.0
# Extend_penalty: 0.5
#
# Length: 131
# Identity:     112/131 (85.5%)
# Similarity:   112/131 (85.5%)
# Gaps:          19/131 (14.5%)
# Score: 591.5
#
#
#=======================================

IXI_234            1 TSPASIRPPAGPSSRPAMVSSRRTRPSPPGPRRPTGRPCCSAAPRRPQAT     50
                     |||||||||||||||         ||||||||||||||||||||||||||
IXI_235            1 TSPASIRPPAGPSSR---------RPSPPGPRRPTGRPCCSAAPRRPQAT     41

IXI_234           51 GGWKTCSGTCTTSTSTRHRGRSGWSARTTTAACLRASRKSMRAACSRSAG    100
                     ||||||||||||||||||||||||          ||||||||||||||||
IXI_235           42 GGWKTCSGTCTTSTSTRHRGRSGW----------RASRKSMRAACSRSAG     81

IXI_234          101 SRPNRFAPTLMSSCITSTTGPPAWAGDRSHE    131
                     |||||||||||||||||||||||||||||||
IXI_235           82 SRPNRFAPTLMSSCITSTTGPPAWAGDRSHE    112


#---------------------------------------
#---------------------------------------       
\end{minted}
As this output file contains only one alignment, we can use \verb|Align.read| to extract it directly. Here, instead we will use \verb|Align.parse| so we can see the metadata of this \verb|water| run:
%doctest ../Tests/Emboss lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("water.txt", "emboss")
\end{minted}
The \verb|metadata| attribute of \verb|alignments| stores the information shown in the header of the file, including the program used to generate the output, the date and time the program was run, the output file name, and the specific alignment file format that was used (assumed to be \verb|srspair| by default):
%cont-doctest
\begin{minted}{pycon}
>>> alignments.metadata
{'Align_format': 'srspair', 'Program': 'water', 'Rundate': 'Wed Jan 16 17:23:19 2002', 'Report_file': 'stdout'}
\end{minted}
To pull out the alignment, we use
%cont-doctest
\begin{minted}{pycon}
>>> alignment = next(alignments)
>>> alignment  # doctest: +ELLIPSIS
<Alignment object (2 rows x 131 columns) at ...>
>>> alignment.shape
(2, 131)
>>> print(alignment)
IXI_234           0 TSPASIRPPAGPSSRPAMVSSRRTRPSPPGPRRPTGRPCCSAAPRRPQATGGWKTCSGTC
                  0 |||||||||||||||---------||||||||||||||||||||||||||||||||||||
IXI_235           0 TSPASIRPPAGPSSR---------RPSPPGPRRPTGRPCCSAAPRRPQATGGWKTCSGTC
<BLANKLINE>
IXI_234          60 TTSTSTRHRGRSGWSARTTTAACLRASRKSMRAACSRSAGSRPNRFAPTLMSSCITSTTG
                 60 ||||||||||||||----------||||||||||||||||||||||||||||||||||||
IXI_235          51 TTSTSTRHRGRSGW----------RASRKSMRAACSRSAGSRPNRFAPTLMSSCITSTTG
<BLANKLINE>
IXI_234         120 PPAWAGDRSHE 131
                120 ||||||||||| 131
IXI_235         101 PPAWAGDRSHE 112
<BLANKLINE>
>>> alignment.coordinates
array([[  0,  15,  24,  74,  84, 131],
       [  0,  15,  15,  65,  65, 112]])
\end{minted}
We can use indices to extract specific parts of the alignment:
%cont-doctest
\begin{minted}{pycon}
>>> alignment[0]
'TSPASIRPPAGPSSRPAMVSSRRTRPSPPGPRRPTGRPCCSAAPRRPQATGGWKTCSGTCTTSTSTRHRGRSGWSARTTTAACLRASRKSMRAACSRSAGSRPNRFAPTLMSSCITSTTGPPAWAGDRSHE'
>>> alignment[1]
'TSPASIRPPAGPSSR---------RPSPPGPRRPTGRPCCSAAPRRPQATGGWKTCSGTCTTSTSTRHRGRSGW----------RASRKSMRAACSRSAGSRPNRFAPTLMSSCITSTTGPPAWAGDRSHE'
>>> alignment[1, 10:30]
'GPSSR---------RPSPPG'
\end{minted}
The \verb|annotations| attribute of the \verb|alignment| stores the information associated with this alignment specifically:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.annotations
{'Matrix': 'EBLOSUM62', 'Gap_penalty': 10.0, 'Extend_penalty': 0.5, 'Identity': 112, 'Similarity': 112, 'Gaps': 19, 'Score': 591.5}
\end{minted}
The number of gaps, identities, and mismatches can also be obtained by calling the \verb|counts| method on the \verb|alignment| object:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.counts()
AlignmentCounts(gaps=19, identities=112, mismatches=0)
\end{minted}
where \verb|AlignmentCounts| is a \verb|namedtuple| in the \verb|collections| module in Python's standard library.

The consensus line shown between the two sequences is stored in the \verb|column_annotations| attribute:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.column_annotations
{'emboss_consensus': '|||||||||||||||         ||||||||||||||||||||||||||||||||||||||||||||||||||          |||||||||||||||||||||||||||||||||||||||||||||||'}
\end{minted}
Use the \verb|format| function (or the \verb|format| method) to print the alignment in other formats, for example in the PHYLIP format (see section~\ref{subsec:align_phylip}):
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "phylip"))
2 131
IXI_234   TSPASIRPPAGPSSRPAMVSSRRTRPSPPGPRRPTGRPCCSAAPRRPQATGGWKTCSGTCTTSTSTRHRGRSGWSARTTTAACLRASRKSMRAACSRSAGSRPNRFAPTLMSSCITSTTGPPAWAGDRSHE
IXI_235   TSPASIRPPAGPSSR---------RPSPPGPRRPTGRPCCSAAPRRPQATGGWKTCSGTCTTSTSTRHRGRSGW----------RASRKSMRAACSRSAGSRPNRFAPTLMSSCITSTTGPPAWAGDRSHE
<BLANKLINE>
\end{minted}
We can use \verb|alignment.sequences| to get the individual sequences. However, as this is a pairwise alignment, we can also use \verb|alignment.target| and \verb|alignment.query| to get the target and query sequences:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.target
SeqRecord(seq=Seq('TSPASIRPPAGPSSRPAMVSSRRTRPSPPGPRRPTGRPCCSAAPRRPQATGGWK...SHE'), id='IXI_234', name='<unknown name>', description='<unknown description>', dbxrefs=[])
>>> alignment.query
SeqRecord(seq=Seq('TSPASIRPPAGPSSRRPSPPGPRRPTGRPCCSAAPRRPQATGGWKTCSGTCTTS...SHE'), id='IXI_235', name='<unknown name>', description='<unknown description>', dbxrefs=[])
\end{minted}
Currently, Biopython does not support writing sequence alignments in the output formats defined by EMBOSS.

\subsection{GCG Multiple Sequence Format (MSF)}
\label{subsec:align_msf}

The Multiple Sequence Format (MSF) was created to store multiple sequence alignments generated by the GCG (Genetics Computer Group) set of programs. The file \verb|W_prot.msf| in the \verb|Tests/msf| directory of the Biopython distribution is an example of a sequence alignment file in the MSF format This file shows an alignment of 11 protein sequences:

\begin{minted}{text}
!!AA_MULTIPLE_ALIGNMENT

   MSF: 99  Type: P  Oct 18, 2017  11:35  Check: 0 ..

 Name: W*01:01:01:01    Len:    99  Check: 7236  Weight:  1.00
 Name: W*01:01:01:02    Len:    99  Check: 7236  Weight:  1.00
 Name: W*01:01:01:03    Len:    99  Check: 7236  Weight:  1.00
 Name: W*01:01:01:04    Len:    99  Check: 7236  Weight:  1.00
 Name: W*01:01:01:05    Len:    99  Check: 7236  Weight:  1.00
 Name: W*01:01:01:06    Len:    99  Check: 7236  Weight:  1.00
 Name: W*02:01          Len:    93  Check: 9483  Weight:  1.00
 Name: W*03:01:01:01    Len:    93  Check: 9974  Weight:  1.00
 Name: W*03:01:01:02    Len:    93  Check: 9974  Weight:  1.00
 Name: W*04:01          Len:    93  Check: 9169  Weight:  1.00
 Name: W*05:01          Len:    99  Check: 7331  Weight:  1.00
//

  W*01:01:01:01  GLTPFNGYTA ATWTRTAVSS VGMNIPYHGA SYLVRNQELR SWTAADKAAQ
  W*01:01:01:02  GLTPFNGYTA ATWTRTAVSS VGMNIPYHGA SYLVRNQELR SWTAADKAAQ
  W*01:01:01:03  GLTPFNGYTA ATWTRTAVSS VGMNIPYHGA SYLVRNQELR SWTAADKAAQ
  W*01:01:01:04  GLTPFNGYTA ATWTRTAVSS VGMNIPYHGA SYLVRNQELR SWTAADKAAQ
  W*01:01:01:05  GLTPFNGYTA ATWTRTAVSS VGMNIPYHGA SYLVRNQELR SWTAADKAAQ
  W*01:01:01:06  GLTPFNGYTA ATWTRTAVSS VGMNIPYHGA SYLVRNQELR SWTAADKAAQ
        W*02:01  GLTPSNGYTA ATWTRTAASS VGMNIPYDGA SYLVRNQELR SWTAADKAAQ
  W*03:01:01:01  GLTPSSGYTA ATWTRTAVSS VGMNIPYHGA SYLVRNQELR SWTAADKAAQ
  W*03:01:01:02  GLTPSSGYTA ATWTRTAVSS VGMNIPYHGA SYLVRNQELR SWTAADKAAQ
        W*04:01  GLTPSNGYTA ATWTRTAASS VGMNIPYDGA SYLVRNQELR SWTAADKAAQ
        W*05:01  GLTPSSGYTA ATWTRTAVSS VGMNIPYHGA SYLVRNQELR SWTAADKAAQ

  W*01:01:01:01  MPWRRNRQSC SKPTCREGGR SGSAKSLRMG RRGCSAQNPK DSHDPPPHL
  W*01:01:01:02  MPWRRNRQSC SKPTCREGGR SGSAKSLRMG RRGCSAQNPK DSHDPPPHL
  W*01:01:01:03  MPWRRNRQSC SKPTCREGGR SGSAKSLRMG RRGCSAQNPK DSHDPPPHL
  W*01:01:01:04  MPWRRNRQSC SKPTCREGGR SGSAKSLRMG RRGCSAQNPK DSHDPPPHL
  W*01:01:01:05  MPWRRNRQSC SKPTCREGGR SGSAKSLRMG RRGCSAQNPK DSHDPPPHL
  W*01:01:01:06  MPWRRNRQSC SKPTCREGGR SGSAKSLRMG RRGCSAQNPK DSHDPPPHL
        W*02:01  MPWRRNMQSC SKPTCREGGR SGSAKSLRMG RRRCTAQNPK RLT
  W*03:01:01:01  MPWRRNRQSC SKPTCREGGR SGSAKSLRMG RRGCSAQNPK RLT
  W*03:01:01:02  MPWRRNRQSC SKPTCREGGR SGSAKSLRMG RRGCSAQNPK RLT
        W*04:01  MPWRRNMQSC SKPTCREGGR SGSAKSLRMG RRGCSAQNPK RLT
        W*05:01  MPWRRNRQSC SKPTCREGGR SGSAKSLRMG RRGCSAQNPK DSHDPPPHL
\end{minted}
To parse this file with Biopython, use
%doctest ../Tests/msf lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignment = Align.read("W_prot.msf", "msf")
\end{minted}
The parser skips all lines up to and including the line starting with "\verb|MSF:|". The following lines (until the "\verb|//|" demarcation) are read by the parser to verify the length of each sequence. The alignment section (after the "\verb|//|" demarcation) is read by the parser and stored as an \verb|Alignment| object:
%cont-doctest
\begin{minted}{pycon}
>>> alignment  # doctest: +ELLIPSIS
<Alignment object (11 rows x 99 columns) at ...>
>>> print(alignment)
W*01:01:0         0 GLTPFNGYTAATWTRTAVSSVGMNIPYHGASYLVRNQELRSWTAADKAAQMPWRRNRQSC
W*01:01:0         0 GLTPFNGYTAATWTRTAVSSVGMNIPYHGASYLVRNQELRSWTAADKAAQMPWRRNRQSC
W*01:01:0         0 GLTPFNGYTAATWTRTAVSSVGMNIPYHGASYLVRNQELRSWTAADKAAQMPWRRNRQSC
W*01:01:0         0 GLTPFNGYTAATWTRTAVSSVGMNIPYHGASYLVRNQELRSWTAADKAAQMPWRRNRQSC
W*01:01:0         0 GLTPFNGYTAATWTRTAVSSVGMNIPYHGASYLVRNQELRSWTAADKAAQMPWRRNRQSC
W*01:01:0         0 GLTPFNGYTAATWTRTAVSSVGMNIPYHGASYLVRNQELRSWTAADKAAQMPWRRNRQSC
W*02:01           0 GLTPSNGYTAATWTRTAASSVGMNIPYDGASYLVRNQELRSWTAADKAAQMPWRRNMQSC
W*03:01:0         0 GLTPSSGYTAATWTRTAVSSVGMNIPYHGASYLVRNQELRSWTAADKAAQMPWRRNRQSC
W*03:01:0         0 GLTPSSGYTAATWTRTAVSSVGMNIPYHGASYLVRNQELRSWTAADKAAQMPWRRNRQSC
W*04:01           0 GLTPSNGYTAATWTRTAASSVGMNIPYDGASYLVRNQELRSWTAADKAAQMPWRRNMQSC
W*05:01           0 GLTPSSGYTAATWTRTAVSSVGMNIPYHGASYLVRNQELRSWTAADKAAQMPWRRNRQSC
<BLANKLINE>
W*01:01:0        60 SKPTCREGGRSGSAKSLRMGRRGCSAQNPKDSHDPPPHL 99
W*01:01:0        60 SKPTCREGGRSGSAKSLRMGRRGCSAQNPKDSHDPPPHL 99
W*01:01:0        60 SKPTCREGGRSGSAKSLRMGRRGCSAQNPKDSHDPPPHL 99
W*01:01:0        60 SKPTCREGGRSGSAKSLRMGRRGCSAQNPKDSHDPPPHL 99
W*01:01:0        60 SKPTCREGGRSGSAKSLRMGRRGCSAQNPKDSHDPPPHL 99
W*01:01:0        60 SKPTCREGGRSGSAKSLRMGRRGCSAQNPKDSHDPPPHL 99
W*02:01          60 SKPTCREGGRSGSAKSLRMGRRRCTAQNPKRLT------ 93
W*03:01:0        60 SKPTCREGGRSGSAKSLRMGRRGCSAQNPKRLT------ 93
W*03:01:0        60 SKPTCREGGRSGSAKSLRMGRRGCSAQNPKRLT------ 93
W*04:01          60 SKPTCREGGRSGSAKSLRMGRRGCSAQNPKRLT------ 93
W*05:01          60 SKPTCREGGRSGSAKSLRMGRRGCSAQNPKDSHDPPPHL 99
<BLANKLINE>
\end{minted}
The sequences and their names are stored in the \verb|alignment.sequences| attribute:
%cont-doctest
\begin{minted}{pycon}
>>> len(alignment.sequences)
11
>>> alignment.sequences[0].id
'W*01:01:01:01'
>>> alignment.sequences[0].seq
Seq('GLTPFNGYTAATWTRTAVSSVGMNIPYHGASYLVRNQELRSWTAADKAAQMPWR...PHL')
\end{minted}
The alignment coordinates are stored in the \verb|alignment.coordinates| attribute:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.coordinates
array([[ 0, 93, 99],
       [ 0, 93, 99],
       [ 0, 93, 99],
       [ 0, 93, 99],
       [ 0, 93, 99],
       [ 0, 93, 99],
       [ 0, 93, 93],
       [ 0, 93, 93],
       [ 0, 93, 93],
       [ 0, 93, 93],
       [ 0, 93, 99]])
\end{minted}
Currently, Biopython does not support writing sequence alignments in the MSF format.

\subsection{Exonerate}
\label{subsec:align_exonerate}

Exonerate is a generic program for pairwise sequence alignments~\cite{slater2005}. The sequence alignments found by Exonerate can be output in a human-readable form, in the "cigar" (Compact Idiosyncratic Gapped Alignment Report) format, or in the "vulgar" (Verbose Useful Labelled Gapped Alignment Report) format. The user can request to include one or more of these formats in the output. The parser in \verb|Bio.Align| can only parse alignments in the cigar or vulgar formats, and will not parse output that includes alignments in human-readable format.

The file \verb|exn_22_m_cdna2genome_vulgar.exn| in the Biopython test suite is an example of an Exonerate output file showing the alignments in vulgar format:
\begin{minted}{text}
Command line: [exonerate -m cdna2genome ../scer_cad1.fa /media/Waterloo/Downloads/genomes/scer_s288c/scer_s288c.fa --bestn 3 --showalignment no --showcigar no --showvulgar yes]
Hostname: [blackbriar]
vulgar: gi|296143771|ref|NM_001180731.1| 0 1230 + gi|330443520|ref|NC_001136.10| 1319275 1318045 - 6146 M 1 1 C 3 3 M 1226 1226
vulgar: gi|296143771|ref|NM_001180731.1| 1230 0 - gi|330443520|ref|NC_001136.10| 1318045 1319275 + 6146 M 129 129 C 3 3 M 1098 1098
vulgar: gi|296143771|ref|NM_001180731.1| 0 516 + gi|330443688|ref|NC_001145.3| 85010 667216 + 518 M 11 11 G 1 0 M 15 15 G 2 0 M 4 4 G 1 0 M 1 1 G 1 0 M 8 8 G 4 0 M 17 17 5 0 2 I 0 168904 3 0 2 M 4 4 G 0 1 M 8 8 G 2 0 M 3 3 G 1 0 M 33 33 G 0 2 M 7 7 G 0 1 M 102 102 5 0 2 I 0 96820 3 0 2 M 14 14 G 0 2 M 10 10 G 2 0 M 5 5 G 0 2 M 10 10 G 2 0 M 4 4 G 0 1 M 20 20 G 1 0 M 15 15 G 0 1 M 5 5 G 3 0 M 4 4 5 0 2 I 0 122114 3 0 2 M 20 20 G 0 5 M 6 6 5 0 2 I 0 193835 3 0 2 M 12 12 G 0 2 M 5 5 G 1 0 M 7 7 G 0 2 M 1 1 G 0 1 M 12 12 C 75 75 M 6 6 G 1 0 M 4 4 G 0 1 M 2 2 G 0 1 M 3 3 G 0 1 M 41 41
-- completed exonerate analysis
\end{minted}
This file includes three alignments. To parse this file, use
%doctest ../Tests/Exonerate lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("exn_22_m_cdna2genome_vulgar.exn", "exonerate")
\end{minted}
The dictionary \verb|alignments.metadata| stores general information about these alignments, shown at the top of the output file:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.metadata  # doctest: +NORMALIZE_WHITESPACE
{'Program': 'exonerate',
 'Command line': 'exonerate -m cdna2genome ../scer_cad1.fa /media/Waterloo/Downloads/genomes/scer_s288c/scer_s288c.fa --bestn 3 --showalignment no --showcigar no --showvulgar yes',
 'Hostname': 'blackbriar'}
\end{minted}
Now we can iterate over the alignments. The first alignment, with alignment score 6146.0, has no gaps:
%cont-doctest
\begin{minted}{pycon}
>>> alignment = next(alignments)
>>> alignment.score
6146.0
>>> alignment.coordinates
array([[1319275, 1319274, 1319271, 1318045],
       [      0,       1,       4,    1230]])
>>> print(alignment)  # doctest: +ELLIPSIS
gi|330443   1319275 ????????????????????????????????????????????????????????????
                  0 ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
gi|296143         0 ????????????????????????????????????????????????????????????
...
gi|330443   1318075 ?????????????????????????????? 1318045
               1200 ||||||||||||||||||||||||||||||    1230
gi|296143      1200 ??????????????????????????????    1230
<BLANKLINE>
\end{minted}
Note that the target (the first sequence) in the printed alignment is on the reverse strand while the query (the second sequence) is on the forward strand, with the target coordinate decreasing and the query coordinate increasing.
Printing this alignment in \verb|exonerate| format using Python's built-in \verb|format| function writes a vulgar line:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "exonerate"))
vulgar: gi|296143771|ref|NM_001180731.1| 0 1230 + gi|330443520|ref|NC_001136.10| 1319275 1318045 - 6146 M 1 1 C 3 3 M 1226 1226
<BLANKLINE>
\end{minted}
Using the \verb|format| method allows us to request either a vulgar line (default) or a cigar line:
%cont-doctest
\begin{minted}{pycon}
>>> print(alignment.format("exonerate", "vulgar"))
vulgar: gi|296143771|ref|NM_001180731.1| 0 1230 + gi|330443520|ref|NC_001136.10| 1319275 1318045 - 6146 M 1 1 C 3 3 M 1226 1226
<BLANKLINE>
>>> print(alignment.format("exonerate", "cigar"))
cigar: gi|296143771|ref|NM_001180731.1| 0 1230 + gi|330443520|ref|NC_001136.10| 1319275 1318045 - 6146 M 1 M 3 M 1226
<BLANKLINE>
\end{minted}
The vulgar line contains information about the alignment (in the section \verb|M 1 1 C 3 3 M 1226|) that is missing from the cigar line \verb|M 1 M 3 M 1226|. The vulgar line specifies that the alignment starts with a single aligned nucleotides, followed by three aligned nucleotides that form a codon (\verb|C|), followed by 1226 aligned nucleotides. In the cigar line, we see a single aligned nucleotide, followed by three aligned nucleotides, followed by 1226 aligned nucleotides; it does not specify that the three aligned nucleotides form a codon. This information from the vulgar line is stored in the \verb|operations| attribute:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.operations
bytearray(b'MCM')
\end{minted}
See the Exonerate documentation for the definition of other operation codes.

Similarly, the \verb|"vulgar"| or \verb|"cigar"| argument can be used when calling \verb|Bio.Align.write| to write a file with vulgar or cigar alignment lines.

We can print the alignment in BED and PSL format:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "bed"))  # doctest: +NORMALIZE_WHITESPACE
gi|330443520|ref|NC_001136.10|	1318045	1319275	gi|296143771|ref|NM_001180731.1| 6146	-	1318045	1319275	0	3	1226,3,1,	0,1226,1229,
<BLANKLINE>
>>> print(format(alignment, "psl"))  # doctest: +NORMALIZE_WHITESPACE
1230	0	0	0	0	0	0	0	-	gi|296143771|ref|NM_001180731.1|	1230	0	1230	gi|330443520|ref|NC_001136.10|	1319275	1318045	1319275	3	1226,3,1,	0,1226,1229,	1318045,1319271,1319274,
<BLANKLINE>
\end{minted}
The SAM format parser defines its own (optional) \verb|operations| attribute (section~\ref{subsec:align_sam}), which is not quite consistent with the \verb|operations| attribute defined in the Exonerate format parser. As the \verb|operations| attribute is optional, we delete it before printing the alignment in SAM format:
%cont-doctest
\begin{minted}{pycon}
>>> del alignment.operations
>>> print(format(alignment, "sam"))  # doctest: +NORMALIZE_WHITESPACE
gi|296143771|ref|NM_001180731.1|	16	gi|330443520|ref|NC_001136.10|	1318046	255	1226M3M1M	*	0	0	*	*	AS:i:6146
<BLANKLINE>
\end{minted}

The third alignment contains four long gaps:
%cont-doctest
\begin{minted}{pycon}
>>> alignment = next(alignments)  # second alignment
>>> alignment = next(alignments)  # third alignment
>>> print(alignment)  # doctest: +ELLIPSIS
gi|330443     85010 ???????????-???????????????--????-?-????????----????????????
                  0 |||||||||||-|||||||||||||||--||||-|-||||||||----||||||||||||
gi|296143         0 ????????????????????????????????????????????????????????????
<BLANKLINE>
gi|330443     85061 ????????????????????????????????????????????????????????????
                 60 |||||-------------------------------------------------------
gi|296143        60 ?????-------------------------------------------------------
...
gi|330443    666990 ????????????????????????????????????????????????????????????
             582000 --------------------------------------------------||||||||||
gi|296143       346 --------------------------------------------------??????????
<BLANKLINE>
gi|330443    667050 ?????????-??????????????????????????????????????????????????
             582060 ||--|||||-|||||||--|-|||||||||||||||||||||||||||||||||||||||
gi|296143       356 ??--?????????????--?-???????????????????????????????????????
<BLANKLINE>
gi|330443    667109 ??????????????????????????????????????????????????????-?????
             582120 ||||||||||||||||||||||||||||||||||||||||||||||||||||||-||||-
gi|296143       411 ???????????????????????????????????????????????????????????-
<BLANKLINE>
gi|330443    667168 ???????????????????????????????????????????????? 667216
             582180 ||-|||-||||||||||||||||||||||||||||||||||||||||| 582228
gi|296143       470 ??-???-?????????????????????????????????????????    516
<BLANKLINE>
>>> print(format(alignment, "exonerate"))  # doctest: +NORMALIZE_WHITESPACE
vulgar: gi|296143771|ref|NM_001180731.1| 0 516 + gi|330443688|ref|NC_001145.3|
85010 667216 + 518 M 11 11 G 1 0 M 15 15 G 2 0 M 4 4 G 1 0 M 1 1 G 1 0 M 8 8
 G 4 0 M 17 17 5 0 2 I 0 168904 3 0 2 M 4 4 G 0 1 M 8 8 G 2 0 M 3 3 G 1 0
 M 33 33 G 0 2 M 7 7 G 0 1 M 102 102 5 0 2 I 0 96820 3 0 2 M 14 14 G 0 2 M 10 10
 G 2 0 M 5 5 G 0 2 M 10 10 G 2 0 M 4 4 G 0 1 M 20 20 G 1 0 M 15 15 G 0 1 M 5 5
 G 3 0 M 4 4 5 0 2 I 0 122114 3 0 2 M 20 20 G 0 5 M 6 6 5 0 2 I 0 193835 3 0 2
 M 12 12 G 0 2 M 5 5 G 1 0 M 7 7 G 0 2 M 1 1 G 0 1 M 12 12 C 75 75 M 6 6 G 1 0
 M 4 4 G 0 1 M 2 2 G 0 1 M 3 3 G 0 1 M 41 41
<BLANKLINE>
\end{minted}


\subsection{NEXUS}
\label{subsec:align_nexus}

The NEXUS file format~\cite{maddison1997} is used by several programs to store phylogenetic information. This is an example of a file in the NEXUS format (available as \verb|codonposset.nex| in the \verb|Tests/Nexus| subdirectory in the Biopython distribution):
\begin{minted}{text}
#NEXUS
[MacClade 4.05 registered to Computational Biologist, University]


BEGIN DATA;
       DIMENSIONS  NTAX=2 NCHAR=22;
       FORMAT DATATYPE=DNA  MISSING=? GAP=- ;
MATRIX
[                           10        20 ]
[                           .         .  ]

Aegotheles         AAAAAGGCATTGTGGTGGGAAT   [22]
Aerodramus         ?????????TTGTGGTGGGAAT   [13]
;
END;


BEGIN CODONS;
       CODONPOSSET * CodonPositions =
               N: 1-10,
               1: 11-22\3,
               2: 12-22\3,
               3: 13-22\3;
       CODESET  * UNTITLED = Universal: all ;
END;
\end{minted}
In general, files in the NEXUS format can be much more complex. \verb|Bio.Align| relies heavily on NEXUS parser in \verb|Bio.Nexus| (see Chapter~\ref{chapter:phylo}) to extract \verb|Alignment| objects from NEXUS files.

To read the alignment in this NEXUS file, use
%doctest ../Tests/Nexus lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignment = Align.read("codonposset.nex", "nexus")
>>> print(alignment)
Aegothele         0 AAAAAGGCATTGTGGTGGGAAT 22
                  0 .........||||||||||||| 22
Aerodramu         0 ?????????TTGTGGTGGGAAT 22
<BLANKLINE>
>>> alignment.shape
(2, 22)
\end{minted}
The sequences are stored under the \verb|sequences| attribute:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.sequences[0].id
'Aegotheles'
>>> alignment.sequences[0].seq
Seq('AAAAAGGCATTGTGGTGGGAAT')
>>> alignment.sequences[0].annotations
{'molecule_type': 'DNA'}
>>> alignment.sequences[1].id
'Aerodramus'
>>> alignment.sequences[1].seq
Seq('?????????TTGTGGTGGGAAT')
>>> alignment.sequences[1].annotations
{'molecule_type': 'DNA'}
\end{minted}
To print this alignment in the NEXUS format, use
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "nexus"))
#NEXUS
begin data;
dimensions ntax=2 nchar=22;
format datatype=dna missing=? gap=-;
matrix
Aegotheles AAAAAGGCATTGTGGTGGGAAT
Aerodramus ?????????TTGTGGTGGGAAT
;
end;
<BLANKLINE>
\end{minted}
Similarly, you can use \verb|Align.write(alignment, "myfilename.nex", "nexus")| to write the alignment in the NEXUS format to the file \verb|myfilename.nex|.

\subsection{Tabular output from BLAST or FASTA}
\label{subsec:align_tabular}

Alignment output in tabular output is generated by the FASTA aligner~\cite{pearson1988} run with the \verb|-m 8CB| or  \verb|-m 8CC| argument, or by BLAST~\cite{altschul1990} run with the \verb|-outfmt 7| argument.

The file \verb|nucleotide_m8CC.txt| in the \verb|Tests/Fasta| subdirectory of the Biopython source distribution is an example of an output file generated by FASTA with the \verb|-m 8CC| argument:
\begin{minted}{text}
# fasta36 -m 8CC seq/mgstm1.nt seq/gst.nlib
# FASTA 36.3.8h May, 2020
# Query: pGT875  - 657 nt
# Database: seq/gst.nlib
# Fields: query id, subject id, % identity, alignment length, mismatches, gap opens, q. start, q. end, s. start, s. end, evalue, bit score, aln_code
# 12 hits found
pGT875	pGT875	100.00	657	0	0	1	657	38	694	4.6e-191	655.6	657M
pGT875	RABGLTR	79.10	646	135	0	1	646	34	679	1.6e-116	408.0	646M
pGT875	BTGST	59.56	413	167	21	176	594	228	655	1.9e-07	45.7	149M1D7M1I17M3D60M5I6M1I13M2I13M4I30M2I6M2D112M
pGT875	RABGSTB	66.93	127	42	8	159	289	157	287	3.2e-07	45.0	15M2I17M2D11M1I58M1I11M1D7M1D8M
pGT875	OCDHPR	91.30	23	2	1	266	289	2303	2325	0.012	29.7	17M1D6M
...
# FASTA processed 1 queries
\end{minted}
To parse this file, use
%doctest ../Tests/Fasta lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("nucleotide_m8CC.txt", "tabular")
\end{minted}
Information shown in the file header is stored in the \verb|metadata| attribute of \verb|alignments|:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.metadata  # doctest: +NORMALIZE_WHITESPACE
{'Command line': 'fasta36 -m 8CC seq/mgstm1.nt seq/gst.nlib',
 'Program': 'FASTA',
 'Version': '36.3.8h May, 2020',
 'Database': 'seq/gst.nlib'}
\end{minted}
Extract a specific alignment by iterating over the \verb|alignments|. As an example, let's go to the fourth alignment:
%cont-doctest
\begin{minted}{pycon}
>>> alignment = next(alignments)
>>> alignment = next(alignments)
>>> alignment = next(alignments)
>>> alignment = next(alignments)
>>> print(alignment)
RABGSTB         156 ??????????????????????????????????--????????????????????????
                  0 |||||||||||||||--|||||||||||||||||--|||||||||||-||||||||||||
pGT875          158 ???????????????--??????????????????????????????-????????????
<BLANKLINE>
RABGSTB         214 ??????????????????????????????????????????????????????????-?
                 60 ||||||||||||||||||||||||||||||||||||||||||||||-|||||||||||-|
pGT875          215 ??????????????????????????????????????????????-?????????????
<BLANKLINE>
RABGSTB         273 ??????-???????? 287
                120 ||||||-|||||||| 135
pGT875          274 ??????????????? 289
<BLANKLINE>
>>> alignment.coordinates  # doctest: +NORMALIZE_WHITESPACE
array([[156, 171, 173, 190, 190, 201, 202, 260, 261, 272, 272, 279, 279, 287],
       [158, 173, 173, 190, 192, 203, 203, 261, 261, 272, 273, 280, 281, 289]])
>>> alignment.aligned
array([[[156, 171],
        [173, 190],
        [190, 201],
        [202, 260],
        [261, 272],
        [272, 279],
        [279, 287]],
<BLANKLINE>
       [[158, 173],
        [173, 190],
        [192, 203],
        [203, 261],
        [261, 272],
        [273, 280],
        [281, 289]]])
\end{minted}
The sequence information of the target and query sequences is stored in the \verb|target| and \verb|query| attributes (as well as under \verb|alignment.sequences|):
%cont-doctest
\begin{minted}{pycon}
>>> alignment.target
SeqRecord(seq=Seq(None, length=287), id='RABGSTB', name='<unknown name>', description='<unknown description>', dbxrefs=[])
>>> alignment.query
SeqRecord(seq=Seq(None, length=657), id='pGT875', name='<unknown name>', description='<unknown description>', dbxrefs=[])
\end{minted}
Information of the alignment is stored under the \verb|annotations| attribute of the \verb|alignment|:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.annotations  # doctest: +NORMALIZE_WHITESPACE
{'% identity': 66.93,
 'mismatches': 42,
 'gap opens': 8,
 'evalue': 3.2e-07,
 'bit score': 45.0}
\end{minted}
BLAST in particular offers many options to customize tabular output by including or excluding specific columns; see the BLAST documentation for details. This information is stored in the dictionaries \verb|alignment.annotations|, \verb|alignment.target.annotations|, or \verb|alignment.query.annotations|, as appropriate.

\subsection{HH-suite output files}
\label{subsec:align_hhr}

Alignment files in the \verb|hhr| format are generated by \verb+hhsearch+ or \verb+hhblits+ in HH-suite~\cite{steinegger2019}.
As an example, see the file \verb+2uvo_hhblits.hhr+ in Biopython's test suite:

\begin{minted}{text}
Query         2UVO:A|PDBID|CHAIN|SEQUENCE
Match_columns 171
No_of_seqs    1560 out of 4005
Neff          8.3
Searched_HMMs 34
Date          Fri Feb 15 16:34:13 2019
Command       hhblits -i 2uvoAh.fasta -d /pdb70

 No Hit                             Prob E-value P-value  Score    SS Cols Query HMM  Template HMM
  1 2uvo_A Agglutinin isolectin 1; 100.0 3.7E-34 4.8E-38  210.3   0.0  171    1-171     1-171 (171)
  2 2wga   ; lectin (agglutinin);   99.9 1.1E-30 1.4E-34  190.4   0.0  162    2-169     2-163 (164)
  3 1ulk_A Lectin-C; chitin-bindin  99.8 5.2E-24 6.6E-28  148.2   0.0  120    1-124     2-121 (126)
...
 31 4z8i_A BBTPGRP3, peptidoglycan  79.6    0.12 1.5E-05   36.1   0.0   37    1-37      9-54  (236)
 32 1wga   ; lectin (agglutinin);   40.4     2.6 0.00029   25.9   0.0  106   54-163    11-116 (164)

No 1
>2uvo_A Agglutinin isolectin 1; carbohydrate-binding protein, hevein domain, chitin-binding, GERM agglutinin, chitin-binding protein; HET: NDG NAG GOL; 1.40A {Triticum aestivum} PDB: 1wgc_A* 2cwg_A* 2x3t_A* 4aml_A* 7wga_A 9wga_A 2wgc_A 1wgt_A 1k7t_A* 1k7v_A* 1k7u_A 2x52_A* 1t0w_A*
Probab=99.95  E-value=3.7e-34  Score=210.31  Aligned_cols=171  Identities=100%  Similarity=2.050  Sum_probs=166.9

Q 2UVO:A|PDBID|C    1 ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGATCTNNQCCSQYGYCGFGAEYCGAGCQG   80 (171)
Q Consensus         1 ~~cg~~~~~~~c~~~~CCs~~g~CG~~~~~c~~~c~~~~c~~~~~Cg~~~~~~~c~~~~CCs~~g~CG~~~~~c~~~c~~   80 (171)
                      ||||++.++..||++.|||+|+|||.+.+||+++||.+.|++..+|+++++.++|....|||.++||+.+.+||+.+||.
T Consensus         1 ~~cg~~~~~~~c~~~~CCS~~g~Cg~~~~~Cg~gC~~~~c~~~~~cg~~~~~~~c~~~~CCs~~g~Cg~~~~~c~~~c~~   80 (171)
T 2uvo_A            1 ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGATCTNNQCCSQYGYCGFGAEYCGAGCQG   80 (171)
T ss_dssp             CBCBGGGTTBBCGGGCEECTTSBEEBSHHHHSTTCCBSSCSSCCBCBGGGTTBCCSTTCEECTTSBEEBSHHHHSTTCCB
T ss_pred             CCCCCCCCCcCCCCCCeeCCCCeECCCcccccCCccccccccccccCcccCCcccCCccccCCCceeCCCccccCCCccc
Confidence            79999999999999999999999999999999999999999999999999999999999999999999999999999999


Q 2UVO:A|PDBID|C   81 GPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGGCQSGACSTDKPCGKDAGGRVCTNNYCCSKWGSCGIGPGYC  160 (171)
Q Consensus        81 ~~~~~~~~Cg~~~~~~~c~~~~CCS~~G~CG~~~~~C~~~Cq~~~c~~~~~Cg~~~~~~~c~~~~CCS~~G~CG~~~~~C  160 (171)
                      +++++|+.|+...+++.||++.|||.|||||...+||+.+||+++|++|.+|++.+++++|..+.|||+++-||+...||
T Consensus        81 ~~~~~~~~cg~~~~~~~c~~~~CCs~~g~CG~~~~~C~~gCq~~~c~~~~~cg~~~~~~~c~~~~ccs~~g~Cg~~~~~C  160 (171)
T 2uvo_A           81 GPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGGCQSGACSTDKPCGKDAGGRVCTNNYCCSKWGSCGIGPGYC  160 (171)
T ss_dssp             SSCSSCCBCBGGGTTBCCGGGCEECTTSBEEBSHHHHSTTCCBSSCSSCCCCBTTTTTBCCSTTCEECTTSCEEBSHHHH
T ss_pred             ccccccccccccccCCCCCCCcccCCCCccCCCcccccCCCcCCccccccccccccccccCCCCCCcCCCCEecCchhhc
Confidence            99999999999988999999999999999999999999999999999999999999999999999999999999999999


Q 2UVO:A|PDBID|C  161 GAGCQSGGCDG  171 (171)
Q Consensus       161 ~~gCq~~~c~~  171 (171)
                      +++||++.|||
T Consensus       161 ~~~cq~~~~~~  171 (171)
T 2uvo_A          161 GAGCQSGGCDG  171 (171)
T ss_dssp             STTCCBSSCC-
T ss_pred             ccccccCCCCC
Confidence            99999999986


No 2
...


No 32
>1wga   ; lectin (agglutinin); NMR {}
Probab=40.43  E-value=2.6  Score=25.90  Aligned_cols=106  Identities=20%  Similarity=0.652  Sum_probs=54.7

Q 2UVO:A|PDBID|C   54 TCTNNQCCSQYGYCGFGAEYCGAGCQGGPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGGCQSGACSTDKPCG  133 (171)
Q Consensus        54 ~c~~~~CCs~~g~CG~~~~~c~~~c~~~~~~~~~~Cg~~~~~~~c~~~~CCS~~G~CG~~~~~C~~~Cq~~~c~~~~~Cg  133 (171)
                      .|....||.....|......|...|....|.....|...  ...|....||.....|......|...|....+.....|.
T Consensus        11 ~c~~~~cc~~~~~c~~~~~~c~~~c~~~~c~~~~~c~~~--~~~c~~~~cc~~~~~c~~~~~~c~~~c~~~~c~~~~~c~   88 (164)
T 1wga             11 XCXXXXCCXXXXXCXXXXXXCXXXCXXXXCXXXXXCXXX--XXXCXXXXCCXXXXXCXXXXXXCXXXCXXXXCXXXXXCX   88 (164)
T ss_pred             ccccccccccccccccccccccccccccccccccccccc--ccccccccccccccccccccccccccccccccccccccc
Confidence            344556666666666666566555543333223333321  234666677777777777766666655544332223333


Q 2UVO:A|PDBID|C  134 KDAGGRVCTNNYCCSKWGSCGIGPGYCGAG  163 (171)
Q Consensus       134 ~~~~~~~c~~~~CCS~~G~CG~~~~~C~~g  163 (171)
                      ..  ...|....||.....|......|...
T Consensus        89 ~~--~~~c~~~~cc~~~~~c~~~~~~c~~~  116 (164)
T 1wga             89 XX--XXXCXXXXCCXXXXXCXXXXXXCXXX  116 (164)
T ss_pred             cc--cccccccccccccccccccccccccc
Confidence            22  23344455555555555555544433


Done!
\end{minted}

The file contains three sections:
\begin{itemize}
\item A header with general information about the alignments;
\item A summary with one line for each of the alignments obtained;
\item The alignments shown consecutively in detail.
\end{itemize}

To parse this file, use
%doctest ../Tests/HHsuite lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("2uvo_hhblits.hhr", "hhr")
\end{minted}
Most of the header information is stored in the \verb|metadata| attribute of \verb|alignments|:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.metadata  # doctest: +NORMALIZE_WHITESPACE
{'Match_columns': 171,
 'No_of_seqs': (1560, 4005),
 'Neff': 8.3,
 'Searched_HMMs': 34,
 'Rundate': 'Fri Feb 15 16:34:13 2019',
 'Command line': 'hhblits -i 2uvoAh.fasta -d /pdb70'}
\end{minted}
except the query name, which is stored as an attribute:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.query_name
'2UVO:A|PDBID|CHAIN|SEQUENCE'
\end{minted}
as it will reappear in each of the alignments.

Iterate over the alignments:
%cont-doctest
\begin{minted}{pycon}
>>> for alignment in alignments:
...     print(alignment.target.id)  # doctest: +ELLIPSIS
...
2uvo_A
2wga
1ulk_A
...
4z8i_A
1wga
\end{minted}
Let's look at the first alignment in more detail:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.rewind()
>>> alignment = next(alignments)
>>> alignment  # doctest: +ELLIPSIS
<Alignment object (2 rows x 171 columns) at ...>
>>> print(alignment)
2uvo_A            0 ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGATCTNNQC
                  0 ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
2UVO:A|PD         0 ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGATCTNNQC
<BLANKLINE>
2uvo_A           60 CSQYGYCGFGAEYCGAGCQGGPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGG
                 60 ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
2UVO:A|PD        60 CSQYGYCGFGAEYCGAGCQGGPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGG
<BLANKLINE>
2uvo_A          120 CQSGACSTDKPCGKDAGGRVCTNNYCCSKWGSCGIGPGYCGAGCQSGGCDG 171
                120 ||||||||||||||||||||||||||||||||||||||||||||||||||| 171
2UVO:A|PD       120 CQSGACSTDKPCGKDAGGRVCTNNYCCSKWGSCGIGPGYCGAGCQSGGCDG 171
<BLANKLINE>
\end{minted}
The target and query sequences are stored in \verb|alignment.sequences|. As these are pairwise alignments, we can also access them through \verb|alignment.target| and \verb|alignment.query|:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.target is alignment.sequences[0]
True
>>> alignment.query is alignment.sequences[1]
True
\end{minted}
The ID of the query is set from the \verb|alignments.query_name| (note that the query ID printed in the alignment in the \verb|hhr| file is abbreviated):
%cont-doctest
\begin{minted}{pycon}
>>> alignment.query.id
'2UVO:A|PDBID|CHAIN|SEQUENCE'
\end{minted}
The ID of the target is taken from the sequence alignment block (the line starting with \verb|T 2uvo_A|):
\begin{minted}{pycon}
>>> alignment.target.id
'2uvo_A'
\end{minted}
The sequence contents of the target and query are filled in from the information available in this alignment:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.target.seq
Seq('ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGAT...CDG')
>>> alignment.query.seq
Seq('ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGAT...CDG')
\end{minted}
The sequence contents will be incomplete (a partially defined sequence; see Section~\ref{sec:partial-seq}) if the alignment does not extend over the full sequence.

The second line of this alignment block, starting with "\verb|>|", shows the name and description of the Hidden Markov Model from which the target sequence was taken. These are stored under the keys \verb|"hmm_name"| and \verb|"hmm_description"| in the \verb|alignment.target.annotations| dictionary:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.target.annotations  # doctest: +NORMALIZE_WHITESPACE
{'hmm_name': '2uvo_A',
 'hmm_description': 'Agglutinin isolectin 1; carbohydrate-binding protein, hevein domain, chitin-binding, GERM agglutinin, chitin-binding protein; HET: NDG NAG GOL; 1.40A {Triticum aestivum} PDB: 1wgc_A* 2cwg_A* 2x3t_A* 4aml_A* 7wga_A 9wga_A 2wgc_A 1wgt_A 1k7t_A* 1k7v_A* 1k7u_A 2x52_A* 1t0w_A*'}
\end{minted}
The dictionary \verb|alignment.target.letter_annotations| stores the target alignent consensus sequence, the secondary structure as predicted by PSIPRED, and the target secondary structure as determined by DSSP:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.target.letter_annotations  # doctest: +NORMALIZE_WHITESPACE
{'Consensus': '~~cg~~~~~~~c~~~~CCS~~g~Cg~~~~~Cg~gC~~~~c~~~~~cg~~~~~~~c~~~~CCs~~g~Cg~~~~~c~~~c~~~~~~~~~~cg~~~~~~~c~~~~CCs~~g~CG~~~~~C~~gCq~~~c~~~~~cg~~~~~~~c~~~~ccs~~g~Cg~~~~~C~~~cq~~~~~~',
 'ss_pred': 'CCCCCCCCCcCCCCCCeeCCCCeECCCcccccCCccccccccccccCcccCCcccCCccccCCCceeCCCccccCCCcccccccccccccccccCCCCCCCcccCCCCccCCCcccccCCCcCCccccccccccccccccCCCCCCcCCCCEecCchhhcccccccCCCCC',
 'ss_dssp': 'CBCBGGGTTBBCGGGCEECTTSBEEBSHHHHSTTCCBSSCSSCCBCBGGGTTBCCSTTCEECTTSBEEBSHHHHSTTCCBSSCSSCCBCBGGGTTBCCGGGCEECTTSBEEBSHHHHSTTCCBSSCSSCCCCBTTTTTBCCSTTCEECTTSCEEBSHHHHSTTCCBSSCC '}
\end{minted}
In this example, for the query sequence only the consensus sequence is available:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.query.letter_annotations
{'Consensus': '~~cg~~~~~~~c~~~~CCs~~g~CG~~~~~c~~~c~~~~c~~~~~Cg~~~~~~~c~~~~CCs~~g~CG~~~~~c~~~c~~~~~~~~~~Cg~~~~~~~c~~~~CCS~~G~CG~~~~~C~~~Cq~~~c~~~~~Cg~~~~~~~c~~~~CCS~~G~CG~~~~~C~~gCq~~~c~~'}
\end{minted}
The \verb|alignment.annotations| dictionary stores information about the alignment shown on the third line of the alignment block:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.annotations  # doctest: +NORMALIZE_WHITESPACE
{'Probab': 99.95,
 'E-value': 3.7e-34,
 'Score': 210.31,
 'Identities': 100.0,
 'Similarity': 2.05,
 'Sum_probs': 166.9}
\end{minted}
Confidence values for the pairwise alignment are stored under the \verb|"Confidence"| key in the \verb|alignment.column_annotations| dictionary. This dictionary also stores the score for each column, shown between the query and the target section of each alignment block:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.column_annotations  # doctest: +NORMALIZE_WHITESPACE
{'column score': '||||++.++..||++.|||+|+|||.+.+||+++||.+.|++..+|+++++.++|....|||.++||+.+.+||+.+||.+++++|+.|+...+++.||++.|||.|||||...+||+.+||+++|++|.+|++.+++++|..+.|||+++-||+...||+++||++.|||',
 'Confidence': '799999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998899999999999999999999999999999999999999999999999999999999999999999999999999986'}
\end{minted}

\subsection{A2M}
\label{subsec:align_a2m}

A2M files are alignment files created by \verb+align2model+ or \verb+hmmscore+
in the SAM Sequence Alignment and Modeling Software System~\cite{krogh1994,hughey1996}.  An A2M file contains one multiple alignment. The A2M file format is similar to aligned FASTA (see section \ref{subsec:align_fasta}). However, to distinguish insertions from deletions, A2M uses both dashes and periods to represent gaps, and both upper and lower case characters in the aligned sequences.
Matches are represented by upper case letters and deletions by dashes in alignment columns containing matches or deletions only. Insertions are represented by lower case letters, with gaps aligned to the insertion shown as periods.  Header lines start with "\verb+>+" followed by the name of the sequence, and optionally a description.

The file \verb+probcons.a2m+ in Biopython's test suite is an example of an A2M file (see section \ref{subsec:align_fasta} for the same alignment in aligned FASTA format):
\begin{minted}{text}
>plas_horvu
D.VLLGANGGVLVFEPNDFSVKAGETITFKNNAGYPHNVVFDEDAVPSG.VD.VSKISQEEYLTAPGETFSVTLTV...PGTYGFYCEPHAGAGMVGKVT
V
>plas_chlre
-.VKLGADSGALEFVPKTLTIKSGETVNFVNNAGFPHNIVFDEDAIPSG.VN.ADAISRDDYLNAPGETYSVKLTA...AGEYGYYCEPHQGAGMVGKII
V
>plas_anava
-.VKLGSDKGLLVFEPAKLTIKPGDTVEFLNNKVPPHNVVFDAALNPAKsADlAKSLSHKQLLMSPGQSTSTTFPAdapAGEYTFYCEPHRGAGMVGKIT
V
>plas_proho
VqIKMGTDKYAPLYEPKALSISAGDTVEFVMNKVGPHNVIFDK--VPAG.ES.APALSNTKLRIAPGSFYSVTLGT...PGTYSFYCTPHRGAGMVGTIT
V
>azup_achcy
VhMLNKGKDGAMVFEPASLKVAPGDTVTFIPTDK-GHNVETIKGMIPDG.AE.A-------FKSKINENYKVTFTA...PGVYGVKCTPHYGMGMVGVVE
V
\end{minted}
To parse this alignment, use
%doctest ../Tests/Clustalw lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignment = Align.read("probcons.a2m", "a2m")
>>> alignment  # doctest: +ELLIPSIS
<Alignment object (5 rows x 101 columns) at ...>
>>> print(alignment)
plas_horv         0 D-VLLGANGGVLVFEPNDFSVKAGETITFKNNAGYPHNVVFDEDAVPSG-VD-VSKISQE
plas_chlr         0 --VKLGADSGALEFVPKTLTIKSGETVNFVNNAGFPHNIVFDEDAIPSG-VN-ADAISRD
plas_anav         0 --VKLGSDKGLLVFEPAKLTIKPGDTVEFLNNKVPPHNVVFDAALNPAKSADLAKSLSHK
plas_proh         0 VQIKMGTDKYAPLYEPKALSISAGDTVEFVMNKVGPHNVIFDK--VPAG-ES-APALSNT
azup_achc         0 VHMLNKGKDGAMVFEPASLKVAPGDTVTFIPTDK-GHNVETIKGMIPDG-AE-A------
<BLANKLINE>
plas_horv        57 EYLTAPGETFSVTLTV---PGTYGFYCEPHAGAGMVGKVTV 95
plas_chlr        56 DYLNAPGETYSVKLTA---AGEYGYYCEPHQGAGMVGKIIV 94
plas_anav        58 QLLMSPGQSTSTTFPADAPAGEYTFYCEPHRGAGMVGKITV 99
plas_proh        56 KLRIAPGSFYSVTLGT---PGTYSFYCTPHRGAGMVGTITV 94
azup_achc        51 -FKSKINENYKVTFTA---PGVYGVKCTPHYGMGMVGVVEV 88
<BLANKLINE>
\end{minted}
The parser analyzes the pattern of dashes, periods, and lower and upper case letters in the A2M file to determine if a column is an match/mismatch/deletion ("\verb|D|") or an insertion ("\verb|I|"). This information is stored under the \verb+match+ key of the \verb+alignment.column_annotations+ dictionary:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.column_annotations
{'state': 'DIDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDIDDIDDDDDDDDDDDDDDDDDDDDDDDIIIDDDDDDDDDDDDDDDDDDDDDD'}
\end{minted}
As the state information is stored in the \verb+alignment+, we can print the alignment in the A2M format:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "a2m"))
>plas_horvu
D.VLLGANGGVLVFEPNDFSVKAGETITFKNNAGYPHNVVFDEDAVPSG.VD.VSKISQEEYLTAPGETFSVTLTV...PGTYGFYCEPHAGAGMVGKVTV
>plas_chlre
-.VKLGADSGALEFVPKTLTIKSGETVNFVNNAGFPHNIVFDEDAIPSG.VN.ADAISRDDYLNAPGETYSVKLTA...AGEYGYYCEPHQGAGMVGKIIV
>plas_anava
-.VKLGSDKGLLVFEPAKLTIKPGDTVEFLNNKVPPHNVVFDAALNPAKsADlAKSLSHKQLLMSPGQSTSTTFPAdapAGEYTFYCEPHRGAGMVGKITV
>plas_proho
VqIKMGTDKYAPLYEPKALSISAGDTVEFVMNKVGPHNVIFDK--VPAG.ES.APALSNTKLRIAPGSFYSVTLGT...PGTYSFYCTPHRGAGMVGTITV
>azup_achcy
VhMLNKGKDGAMVFEPASLKVAPGDTVTFIPTDK-GHNVETIKGMIPDG.AE.A-------FKSKINENYKVTFTA...PGVYGVKCTPHYGMGMVGVVEV
<BLANKLINE>
\end{minted}
Similarly, the alignment can be written in the A2M format to an output file using \verb|Align.write| (see section~\ref{subsec:align_writing}).

\subsection{Mauve eXtended Multi-FastA (xmfa) format}
\label{subsec:align_mauve}

Mauve~\cite{darling2004} is a software package for constructing multiple genome alignments. These alignments are stored in the eXtended Multi-FastA (xmfa) format.
Depending on how exactly \verb|progressiveMauve| (the aligner program in Mauve) was called, the xmfa format is slightly different.

If \verb|progressiveMauve| is called with a single sequence input file, as in
\begin{minted}{text}
progressiveMauve combined.fasta  --output=combined.xmfa ...
\end{minted}
where \verb|combined.fasta| contains the genome sequences:
\begin{minted}{text}
>equCab1
GAAAAGGAAAGTACGGCCCGGCCACTCCGGGTGTGTGCTAGGAGGGCTTA
>mm9
GAAGAGGAAAAGTAGATCCCTGGCGTCCGGAGCTGGGACGT
>canFam2
CAAGCCCTGCGCGCTCAGCCGGAGTGTCCCGGGCCCTGCTTTCCTTTTC
\end{minted}
then the output file \verb|combined.xmfa| is as follows:
\begin{minted}{text}
#FormatVersion Mauve1
#Sequence1File	combined.fa
#Sequence1Entry	1
#Sequence1Format	FastA
#Sequence2File	combined.fa
#Sequence2Entry	2
#Sequence2Format	FastA
#Sequence3File	combined.fa
#Sequence3Entry	3
#Sequence3Format	FastA
#BackboneFile	combined.xmfa.bbcols
> 1:2-49 - combined.fa
AAGCCCTCCTAGCACACACCCGGAGTGG-CCGGGCCGTACTTTCCTTTT
> 2:0-0 + combined.fa
-------------------------------------------------
> 3:2-48 + combined.fa
AAGCCCTGC--GCGCTCAGCCGGAGTGTCCCGGGCCCTGCTTTCCTTTT
=
> 1:1-1 + combined.fa
G
=
> 1:50-50 + combined.fa
A
=
> 2:1-41 + combined.fa
GAAGAGGAAAAGTAGATCCCTGGCGTCCGGAGCTGGGACGT
=
> 3:1-1 + combined.fa
C
=
> 3:49-49 + combined.fa
C
=
\end{minted}
with numbers (1, 2, 3) referring to the input genome sequences for horse (\verb+equCab1+), mouse (\verb+mm9+), and dog (\verb+canFam2+), respectively.
This xmfa file consists of six alignment blocks, separated by \verb|=| characters. Use \verb|Align.parse| to extract these alignments:
%doctest ../Tests/Mauve lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("combined.xmfa", "mauve")
\end{minted}
The file header data are stored in the \verb|metadata| attribute:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.metadata  # doctest: +NORMALIZE_WHITESPACE
{'FormatVersion': 'Mauve1',
 'BackboneFile': 'combined.xmfa.bbcols',
 'File': 'combined.fa'}
\end{minted}
The \verb|identifiers| attribute stores the sequence identifiers for the three sequences, which in this case is the three numbers:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.identifiers
['0', '1', '2']
\end{minted}
These identifiers are used in the individual alignments:
%cont-doctest
\begin{minted}{pycon}
>>> for alignment in alignments:
...     print([record.id for record in alignment.sequences])
...     print(alignment)
...     print("******")
...
['0', '1', '2']
0                49 AAGCCCTCCTAGCACACACCCGGAGTGG-CCGGGCCGTACTTTCCTTTT  1
1                 0 -------------------------------------------------  0
2                 1 AAGCCCTGC--GCGCTCAGCCGGAGTGTCCCGGGCCCTGCTTTCCTTTT 48
<BLANKLINE>
******
['0']
0                 0 G 1
<BLANKLINE>
******
['0']
0                49 A 50
<BLANKLINE>
******
['1']
1                 0 GAAGAGGAAAAGTAGATCCCTGGCGTCCGGAGCTGGGACGT 41
<BLANKLINE>
******
['2']
2                 0 C 1
<BLANKLINE>
******
['2']
2                48 C 49
<BLANKLINE>
******
\end{minted}
Note that only the first block is a real alignment; the other blocks contain only a single sequence. By including these blocks, the xmfa file contains the full sequence that was provided in the \verb|combined.fa| input file.

If \verb|progressiveMauve| is called with a separate input file for each genome, as in
\begin{minted}{text}
progressiveMauve equCab1.fa canFam2.fa mm9.fa --output=separate.xmfa ...
\end{minted}
where each Fasta file contains the genome sequence for one species only, then the output file \verb|separate.xmfa| is as follows:
\begin{minted}{text}
#FormatVersion Mauve1
#Sequence1File	equCab1.fa
#Sequence1Format	FastA
#Sequence2File	canFam2.fa
#Sequence2Format	FastA
#Sequence3File	mm9.fa
#Sequence3Format	FastA
#BackboneFile	separate.xmfa.bbcols
> 1:1-50 - equCab1.fa
TAAGCCCTCCTAGCACACACCCGGAGTGGCC-GGGCCGTAC-TTTCCTTTTC
> 2:1-49 + canFam2.fa
CAAGCCCTGC--GCGCTCAGCCGGAGTGTCCCGGGCCCTGC-TTTCCTTTTC
> 3:1-19 - mm9.fa
---------------------------------GGATCTACTTTTCCTCTTC
=
> 3:20-41 + mm9.fa
CTGGCGTCCGGAGCTGGGACGT
=
\end{minted}
The identifiers \verb+equCab1+ for horse, \verb+mm9+ for mouse, and \verb+canFam2+ for dog are now shown explicitly in the output file.
This xmfa file consists of two alignment blocks, separated by \verb|=| characters. Use \verb|Align.parse| to extract these alignments:
%doctest ../Tests/Mauve lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("separate.xmfa", "mauve")
\end{minted}
The file header data now does not include the input file name:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.metadata  # doctest: +NORMALIZE_WHITESPACE
{'FormatVersion': 'Mauve1',
 'BackboneFile': 'separate.xmfa.bbcols'}
\end{minted}
The \verb|identifiers| attribute stores the sequence identifiers for the three sequences:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.identifiers
['equCab1.fa', 'canFam2.fa', 'mm9.fa']
\end{minted}
These identifiers are used in the individual alignments:
%cont-doctest
\begin{minted}{pycon}
>>> for alignment in alignments:
...     print([record.id for record in alignment.sequences])
...     print(alignment)
...     print("******")
...
['equCab1.fa', 'canFam2.fa', 'mm9.fa']
equCab1.f        50 TAAGCCCTCCTAGCACACACCCGGAGTGGCC-GGGCCGTAC-TTTCCTTTTC  0
canFam2.f         0 CAAGCCCTGC--GCGCTCAGCCGGAGTGTCCCGGGCCCTGC-TTTCCTTTTC 49
mm9.fa           19 ---------------------------------GGATCTACTTTTCCTCTTC  0
<BLANKLINE>
******
['mm9.fa']
mm9.fa           19 CTGGCGTCCGGAGCTGGGACGT 41
<BLANKLINE>
******
\end{minted}

To output the alignments in Mauve format, use \verb|Align.write|:
%cont-doctest
\begin{minted}{pycon}
>>> from io import StringIO
>>> stream = StringIO()
>>> alignments = Align.parse("separate.xmfa", "mauve")
>>> Align.write(alignments, stream, "mauve")
2
>>> print(stream.getvalue())  # doctest: +NORMALIZE_WHITESPACE
#FormatVersion Mauve1
#Sequence1File	equCab1.fa
#Sequence1Format	FastA
#Sequence2File	canFam2.fa
#Sequence2Format	FastA
#Sequence3File	mm9.fa
#Sequence3Format	FastA
#BackboneFile	separate.xmfa.bbcols
> 1:1-50 - equCab1.fa
TAAGCCCTCCTAGCACACACCCGGAGTGGCC-GGGCCGTAC-TTTCCTTTTC
> 2:1-49 + canFam2.fa
CAAGCCCTGC--GCGCTCAGCCGGAGTGTCCCGGGCCCTGC-TTTCCTTTTC
> 3:1-19 - mm9.fa
---------------------------------GGATCTACTTTTCCTCTTC
=
> 3:20-41 + mm9.fa
CTGGCGTCCGGAGCTGGGACGT
=
<BLANKLINE>
\end{minted}
Here, the writer makes use of the information stored in \verb+alignments.metadata+ and \verb+alignments.identifiers+ to create this format.
If your \verb|alignments| object does not have these attributes, you can provide them as keyword arguments to \verb+Align.write+:
%cont-doctest
\begin{minted}{pycon}
>>> stream = StringIO()
>>> alignments = Align.parse("separate.xmfa", "mauve")
>>> metadata = alignments.metadata
>>> identifiers = alignments.identifiers
>>> alignments = list(alignments)  # this drops the attributes
>>> alignments.metadata  # doctest: +ELLIPSIS
Traceback (most recent call last):
 ...
AttributeError: 'list' object has no attribute 'metadata'
>>> alignments.identifiers  # doctest: +ELLIPSIS
Traceback (most recent call last):
 ...
AttributeError: 'list' object has no attribute 'identifiers'
>>> Align.write(alignments, stream, "mauve", metadata=metadata, identifiers=identifiers)
2
>>> print(stream.getvalue())  # doctest: +NORMALIZE_WHITESPACE
#FormatVersion Mauve1
#Sequence1File	equCab1.fa
#Sequence1Format	FastA
#Sequence2File	canFam2.fa
#Sequence2Format	FastA
#Sequence3File	mm9.fa
#Sequence3Format	FastA
#BackboneFile	separate.xmfa.bbcols
> 1:1-50 - equCab1.fa
TAAGCCCTCCTAGCACACACCCGGAGTGGCC-GGGCCGTAC-TTTCCTTTTC
> 2:1-49 + canFam2.fa
CAAGCCCTGC--GCGCTCAGCCGGAGTGTCCCGGGCCCTGC-TTTCCTTTTC
> 3:1-19 - mm9.fa
---------------------------------GGATCTACTTTTCCTCTTC
=
> 3:20-41 + mm9.fa
CTGGCGTCCGGAGCTGGGACGT
=
<BLANKLINE>
\end{minted}
Python does not allow you to add these attributes to the \verb+alignments+ object directly, as in this example it was converted to a plain list.
However, you can construct an \verb|Alignments| object and add attributes to it (see Section~\ref{sec:alignments}):
%cont-doctest
\begin{minted}{pycon}
>>> alignments = Align.Alignments(alignments)
>>> alignments.metadata = metadata
>>> alignments.identifiers = identifiers
>>> stream = StringIO()
>>> Align.write(alignments, stream, "mauve", metadata=metadata, identifiers=identifiers)
2
>>> print(stream.getvalue())  # doctest: +NORMALIZE_WHITESPACE
#FormatVersion Mauve1
#Sequence1File	equCab1.fa
#Sequence1Format	FastA
#Sequence2File	canFam2.fa
#Sequence2Format	FastA
#Sequence3File	mm9.fa
#Sequence3Format	FastA
#BackboneFile	separate.xmfa.bbcols
> 1:1-50 - equCab1.fa
TAAGCCCTCCTAGCACACACCCGGAGTGGCC-GGGCCGTAC-TTTCCTTTTC
> 2:1-49 + canFam2.fa
CAAGCCCTGC--GCGCTCAGCCGGAGTGTCCCGGGCCCTGC-TTTCCTTTTC
> 3:1-19 - mm9.fa
---------------------------------GGATCTACTTTTCCTCTTC
=
> 3:20-41 + mm9.fa
CTGGCGTCCGGAGCTGGGACGT
=
<BLANKLINE>
\end{minted}
When printing a single alignment in \verb+Mauve+ format, use keyword arguments to provide the metadata and identifiers:
%cont-doctest
\begin{minted}{pycon}
>>> alignment = alignments[0]
>>> print(alignment.format("mauve", metadata=metadata, identifiers=identifiers))
> 1:1-50 - equCab1.fa
TAAGCCCTCCTAGCACACACCCGGAGTGGCC-GGGCCGTAC-TTTCCTTTTC
> 2:1-49 + canFam2.fa
CAAGCCCTGC--GCGCTCAGCCGGAGTGTCCCGGGCCCTGC-TTTCCTTTTC
> 3:1-19 - mm9.fa
---------------------------------GGATCTACTTTTCCTCTTC
=
<BLANKLINE>
\end{minted}

\subsection{Sequence Alignment/Map (SAM)}
\label{subsec:align_sam}

Files in the Sequence Alignment/Map (SAM) format \cite{li2009} store pairwise sequence alignments, usually of next-generation sequencing data against a reference genome. The file \verb+ex1.sam+ in Biopython's test suite is an example of a minimal file in the SAM format. Its first few lines are as follows:
\begin{minted}{text}
EAS56_57:6:190:289:82   69      chr1    100     0       *       =       100     0       CTCAAGGTTGTTGCAAGGGGGTCTATGTGAACAAA     <<<7<<<;<<<<<<<<8;;<7;4<;<;;;;;94<;     MF:i:192
EAS56_57:6:190:289:82   137     chr1    100     73      35M     =       100     0       AGGGGTGCAGAGCCGAGTCACGGGGTTGCCAGCAC     <<<<<<;<<<<<<<<<<;<<;<<<<;8<6;9;;2;     MF:i:64 Aq:i:0  NM:i:0  UQ:i:0  H0:i:1  H1:i:0
EAS51_64:3:190:727:308  99      chr1    103     99      35M     =       263     195     GGTGCAGAGCCGAGTCACGGGGTTGCCAGCACAGG     <<<<<<<<<<<<<<<<<<<<<<<<<<<::<<<844     MF:i:18 Aq:i:73 NM:i:0  UQ:i:0  H0:i:1  H1:i:0
...
\end{minted}
To parse this file, use
%doctest ../Tests/SamBam lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("ex1.sam", "sam")
>>> alignment = next(alignments)
\end{minted}
The \verb|flag| of the first line is 69. According to the SAM/BAM file format specification, lines for which the flag contains the bitwise flag 4 are unmapped. As 69 has the bit corresponding to this position set to True, this sequence is unmapped and was not aligned to the genome (in spite of the first line showing \verb|chr1|). The target of this alignment (or the first item in \verb|alignment.sequences|) is therefore \verb|None|:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.flag
69
>>> bin(69)
'0b1000101'
>>> bin(4)
'0b100'
>>> if alignment.flag & 4:
...     print("unmapped")
... else:
...     print("mapped")
...
unmapped
>>> alignment.sequences
[None, SeqRecord(seq=Seq('CTCAAGGTTGTTGCAAGGGGGTCTATGTGAACAAA'), id='EAS56_57:6:190:289:82', name='<unknown name>', description='', dbxrefs=[])]
>>> alignment.target is None
True
\end{minted}
The second line represents an alignment to chromosome 1:
%cont-doctest
\begin{minted}{pycon}
>>> alignment = next(alignments)
>>> if alignment.flag & 4:
...     print("unmapped")
... else:
...     print("mapped")
...
mapped
>>> alignment.target
SeqRecord(seq=None, id='chr1', name='<unknown name>', description='', dbxrefs=[])
\end{minted}
As this SAM file does not store the genome sequence information for each alignment, we cannot print the alignment. However, we can print the alignment information in SAM format or any other format (such as BED, see section~\ref{subsec:align_bed}) that does not require the target sequence information:
%cont-doctest
\begin{minted}{pycon}
>>> format(alignment, "sam")
'EAS56_57:6:190:289:82\t137\tchr1\t100\t73\t35M\t=\t100\t0\tAGGGGTGCAGAGCCGAGTCACGGGGTTGCCAGCAC\t<<<<<<;<<<<<<<<<<;<<;<<<<;8<6;9;;2;\tMF:i:64\tAq:i:0\tNM:i:0\tUQ:i:0\tH0:i:1\tH1:i:0\n'
>>> format(alignment, "bed")
'chr1\t99\t134\tEAS56_57:6:190:289:82\t0\t+\t99\t134\t0\t1\t35,\t0,\n'
\end{minted}
However, we cannot print the alignment in PSL format (see section~\ref{subsec:align_psl}) as that would require knowing the size of the target sequence chr1:
%cont-doctest
\begin{minted}{pycon}
>>> format(alignment, "psl")  # doctest: +ELLIPSIS
Traceback (most recent call last):
 ...
TypeError: ...
\end{minted}
If you know the size of the target sequences, you can set them by hand:
%cont-doctest
\begin{minted}{pycon}
>>> from Bio.Seq import Seq
>>> from Bio.SeqRecord import SeqRecord
>>> target = SeqRecord(Seq(None, length=1575), id="chr1")
>>> alignment.target = target
>>> format(alignment, "psl")  # doctest: +ELLIPSIS
'35\t0\t0\t0\t0\t0\t0\t0\t+\tEAS56_57:6:190:289:82\t35\t0\t35\tchr1\t1575\t99\t134\t1\t35,\t0,\t99,\n'
\end{minted}

The file \verb+ex1_header.sam+ in Biopython's test suite contains the same alignments, but now also includes a header. Its first few lines are as follows:
\begin{minted}{text}
@HD\tVN:1.3\tSO:coordinate
@SQ\tSN:chr1\tLN:1575
@SQ\tSN:chr2\tLN:1584
EAS56_57:6:190:289:82   69      chr1    100     0       *       =       100     0       CTCAAGGTTGTTGCAAGGGGGTCTATGTGAACAAA     <<<7<<<;<<<<<<<<8;;<7;4<;<;;;;;94<;     MF:i:192
...
\end{minted}
The header stores general information about the alignments, including the size of the target chromosomes. The target information is stored in the \verb|targets| attribute of the \verb|alignments| object:
%doctest ../Tests/SamBam lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("ex1_header.sam", "sam")
>>> len(alignments.targets)
2
>>> alignments.targets[0]
SeqRecord(seq=Seq(None, length=1575), id='chr1', name='<unknown name>', description='', dbxrefs=[])
>>> alignments.targets[1]
SeqRecord(seq=Seq(None, length=1584), id='chr2', name='<unknown name>', description='', dbxrefs=[])
\end{minted}
Other information provided in the header is stored in the \verb|metadata| attribute:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.metadata
{'HD': {'VN': '1.3', 'SO': 'coordinate'}}
\end{minted}
With the target information, we can now also print the alignment in PSL format:
%cont-doctest
\begin{minted}{pycon}
>>> alignment = next(alignments)  # the unmapped sequence; skip it
>>> alignment = next(alignments)
>>> format(alignment, "psl")
'35\t0\t0\t0\t0\t0\t0\t0\t+\tEAS56_57:6:190:289:82\t35\t0\t35\tchr1\t1575\t99\t134\t1\t35,\t0,\t99,\n'
\end{minted}
We can now also print the alignment in human-readable form, but note that the target sequence contents is not available from this file:
%cont-doctest
\begin{minted}{pycon}
>>> print(alignment)
chr1             99 ??????????????????????????????????? 134
                  0 ...................................  35
EAS56_57:         0 AGGGGTGCAGAGCCGAGTCACGGGGTTGCCAGCAC  35
<BLANKLINE>
\end{minted}
Alignments in the file \verb|sam1.sam| in the Biopython test suite contain an additional \verb+MD+ tag that shows how the query sequence differs from the target sequence:
\begin{minted}{text}
@SQ     SN:1    LN:239940
@PG     ID:bwa  PN:bwa  VN:0.6.2-r126
HWI-1KL120:88:D0LRBACXX:1:1101:1780:2146        77      *       0       0       *       *       0       0       GATGGGAAACCCATGGCCGAGTGGGAAGAAACCAGCTGAGGTCACATCACCAGAGGAGGGAGAGTGTGGCCCCTGACTCAGTCCATCAGCTTGTGGAGCTG   @=?DDDDBFFFF7A;E?GGEGE8BB?FF?F>G@F=GIIDEIBCFF<FEFEC@EEEE2?8B8/=@((-;?@2<B9@##########################
...
HWI-1KL120:88:D0LRBACXX:1:1101:2852:2134        137     1       136186  25      101M    =       136186  0       TCACGGTGGCCTGTTGAGGCAGGGGCTCACGCTGACCTCTCTCGGCGTGGGAGGGGCCGGTGTGAGGCAAGGGCTCACGCTGACCTCTCTCGGCGTGGGAG   @C@FFFDFHGHHHJJJIJJJJIJJJGEDHHGGHGBGIIGIIAB@GEE=BDBBCCDD@D@B7@;@DDD?<A?DD728:>8()009>:>>C@>5??B######   XT:A:U  NM:i:5  SM:i:25 AM:i:0  X0:i:1  X1:i:0  XM:i:5  XO:i:0  XG:i:0  MD:Z:25G14G2C34A12A9
\end{minted}
The parser reconstructs the local genome sequence from the \verb|MD| tag, allowing us to see the target sequence explicitly when printing the alignment:
%doctest ../Tests/SamBam lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("sam1.sam", "sam")
>>> for alignment in alignments:
...     if not alignment.flag & 4:  # Skip the unmapped lines
...         break
...
>>> alignment  # doctest: +ELLIPSIS
<Alignment object (2 rows x 101 columns) at ...>
>>> print(alignment)
1            136185 TCACGGTGGCCTGTTGAGGCAGGGGGTCACGCTGACCTCTGTCCGCGTGGGAGGGGCCGG
                  0 |||||||||||||||||||||||||.||||||||||||||.||.||||||||||||||||
HWI-1KL12         0 TCACGGTGGCCTGTTGAGGCAGGGGCTCACGCTGACCTCTCTCGGCGTGGGAGGGGCCGG
<BLANKLINE>
1            136245 TGTGAGGCAAGGGCTCACACTGACCTCTCTCAGCGTGGGAG 136286
                 60 ||||||||||||||||||.||||||||||||.|||||||||    101
HWI-1KL12        60 TGTGAGGCAAGGGCTCACGCTGACCTCTCTCGGCGTGGGAG    101
<BLANKLINE>
\end{minted}

SAM files may include additional information to distinguish simple sequence insertions and deletions from skipped regions of the genome (e.g. introns), hard and soft clipping, and padded sequence regions. As this information cannot be stored in the \verb|coordinates| attribute of an \verb|Alignment| object, and is stored in a dedicated \verb|operations| attribute instead. Let's use the third alignment in this SAM file as an example:
%doctest ../Tests/Blat lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("dna_rna.sam", "sam")
>>> alignment = next(alignments)
>>> alignment = next(alignments)
>>> alignment = next(alignments)
>>> print(format(alignment, "SAM"))  # doctest: +NORMALIZE_WHITESPACE
NR_111921.1	0	chr3	48663768	0	46M1827N82M3376N76M12H	*	0	0	CACGAGAGGAGCGGAGGCGAGGGGTGAACGCGGAGCACTCCAATCGCTCCCAACTAGAGGTCCACCCAGGACCCAGAGACCTGGATTTGAGGCTGCTGGGCGGCAGATGGAGCGATCAGAAGACCAGGAGACGGGAGCTGGAGTGCAGTGGCTGTTCACAAGCGTGAAAGCAAAGATTAAAAAATTTGTTTTTATATTAAAAAA	*	AS:i:1000	NM:i:0
<BLANKLINE>
>>> alignment.coordinates
array([[48663767, 48663813, 48665640, 48665722, 48669098, 48669174],
       [       0,       46,       46,      128,      128,      204]])
>>> alignment.operations
bytearray(b'MNMNM')
>>> alignment.query.annotations["hard_clip_right"]
12
\end{minted}
In this alignment, the cigar string \verb|63M1062N75M468N43M| defines 46 aligned nucleotides, an intron of 1827 nucleotides, 82 aligned nucleotides, an intron of 3376 nucleotides, 76 aligned nucleotides, and 12 hard-clipped nucleotides. These operations are shown in the \verb|operations| attribute, except for hard-clipping, which is stored in \verb|alignment.query.annotations["hard_clip_right"]| (or \verb|alignment.query.annotations["hard_clip_left"]|, if applicable) instead.

To write a SAM file with alignments created from scratch, use an \verb|Alignments| (plural) object (see Section~\ref{sec:alignments}) to store the alignments as well as the metadata and targets:
%doctest . lib:numpy
\begin{minted}{pycon}
>>> from io import StringIO
>>> import numpy as np

>>> from Bio import Align
>>> from Bio.Seq import Seq
>>> from Bio.SeqRecord import SeqRecord

>>> alignments = Align.Alignments()

>>> seq1 = Seq(None, length=10000)
>>> target1 = SeqRecord(seq1, id="chr1")
>>> seq2 = Seq(None, length=15000)
>>> target2 = SeqRecord(seq2, id="chr2")
>>> alignments.targets = [target1, target2]
>>> alignments.metadata = {"HD": {"VN": "1.3", "SO": "coordinate"}}

>>> seqA = Seq(None, length=20)
>>> queryA = SeqRecord(seqA, id="readA")
>>> sequences = [target1, queryA]
>>> coordinates = np.array([[4300, 4320], [0, 20]])
>>> alignment = Align.Alignment(sequences, coordinates)
>>> alignments.append(alignment)

>>> seqB = Seq(None, length=25)
>>> queryB = SeqRecord(seqB, id="readB")
>>> sequences = [target1, queryB]
>>> coordinates = np.array([[5900, 5925], [25, 0]])
>>> alignment = Align.Alignment(sequences, coordinates)
>>> alignments.append(alignment)

>>> seqC = Seq(None, length=40)
>>> queryC = SeqRecord(seqC, id="readC")
>>> sequences = [target2, queryC]
>>> coordinates = np.array([[12300, 12318], [0, 18]])
>>> alignment = Align.Alignment(sequences, coordinates)
>>> alignments.append(alignment)

>>> stream = StringIO()
>>> Align.write(alignments, stream, "sam")
3
>>> print(stream.getvalue())  # doctest: +NORMALIZE_WHITESPACE
@HD	VN:1.3	SO:coordinate
@SQ	SN:chr1	LN:10000
@SQ	SN:chr2	LN:15000
readA	0	chr1	4301	255	20M	*	0	0	*	*
readB	16	chr1	5901	255	25M	*	0	0	*	*
readC	0	chr2	12301	255	18M22S	*	0	0	*       *
<BLANKLINE>
\end{minted}

\subsection{Browser Extensible Data (BED)}
\label{subsec:align_bed}

BED (Browser Extensible Data) files are typically used to store the alignments of gene transcripts to the genome. See the \href{http://genome.cse.ucsc.edu/FAQ/FAQformat.html#format1}{description from UCSC} for a full explanation of the BED format.

BED files have three required fields and nine optional fields. The file \verb|bed12.bed| in subdirectory \verb|Tests/Blat| is an example of a BED file with 12 fields:
\begin{minted}{text}
chr22	1000	5000	mRNA1	960	+	1200	4900	255,0,0	2	567,488,	0,3512,
chr22	2000	6000	mRNA2	900	-	2300	5960	0,255,0	2	433,399,	0,3601,
\end{minted}
To parse this file, use
%doctest ../Tests/Blat lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("bed12.bed", "bed")
>>> len(alignments)
2
>>> for alignment in alignments:
...     print(alignment.coordinates)
...
[[1000 1567 4512 5000]
 [   0  567  567 1055]]
[[2000 2433 5601 6000]
 [ 832  399  399    0]]
\end{minted}
Note that the first sequence ("\verb|mRNA1|") was mapped to the forward strand, while the second sequence ("\verb|mRNA2|") was mapped to the reverse strand.

As a BED file does not store the length of each chromosome, the length of the target sequence is set to its maximum:
% don't include in the doctest, as 32-bit system show a different number
\begin{minted}{pycon}
>>> alignment.target
SeqRecord(seq=Seq(None, length=9223372036854775807), id='chr22', name='<unknown name>', description='', dbxrefs=[])
\end{minted}
The length of the query sequence can be inferred from its alignment information:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.query
SeqRecord(seq=Seq(None, length=832), id='mRNA2', name='<unknown name>', description='', dbxrefs=[])
\end{minted}
The alignment score (field 5) and information stored in fields 7-9 (referred to as \verb|thickStart|, \verb|thickEnd|, and \verb|itemRgb| in the BED format specification) are stored as attributes on the \verb|alignment| object:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.score
900.0
>>> alignment.thickStart
2300
>>> alignment.thickEnd
5960
>>> alignment.itemRgb
'0,255,0'
\end{minted}

To print an alignment in the BED format, you can use Python's built-in \verb|format| function:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "bed"))  # doctest: +NORMALIZE_WHITESPACE
chr22	2000	6000	mRNA2	900	-	2300	5960	0,255,0	2	433,399,	0,3601,
<BLANKLINE>
\end{minted}
or you can use the \verb|format| method of the \verb|alignment| object. This allows you to specify the number of fields to be written as the \verb|bedN| keyword argument:
%cont-doctest
\begin{minted}{pycon}
>>> print(alignment.format("bed"))  # doctest: +NORMALIZE_WHITESPACE
chr22	2000	6000	mRNA2	900	-	2300	5960	0,255,0	2	433,399,	0,3601,
<BLANKLINE>
>>> print(alignment.format("bed", 3))  # doctest: +NORMALIZE_WHITESPACE
chr22	2000	6000
<BLANKLINE>
>>> print(alignment.format("bed", 6))  # doctest: +NORMALIZE_WHITESPACE
chr22	2000	6000	mRNA2	900	-
<BLANKLINE>
\end{minted}
The same keyword argument can be used with \verb|Align.write|:
\begin{minted}{pycon}
>>> alignments.rewind()
>>> Align.write(alignments, "mybed3file.bed", "bed", bedN=3)
2
>>> alignments.rewind()
>>> Align.write(alignments, "mybed6file.bed", "bed", bedN=6)
2
>>> alignments.rewind()
>>> Align.write(alignments, "mybed12file.bed", "bed")
2
\end{minted}


\subsection{bigBed}
\label{subsec:align_bigbed}

The bigBed file format is an indexed binary version of a BED file~\ref{subsec:align_bed}. To create a bigBed file, you can either use the \verb+bedToBigBed+ program from UCSC (\href{https://genome.ucsc.edu/goldenPath/help/bigBed.html}). or you can use Biopython for it by calling the \verb|Bio.Align.write| function with \verb|fmt="bigbed"|. While the two methods should result in identical bigBed files, using \verb+bedToBigBed+ is much faster and may be more reliable, as it is the gold standard. As bigBed files come with a built-in index, it allows you to quickly search a specific genomic region.

As an example, let's parse the bigBed file \verb|dna_rna.bb|, available in the \verb|Tests/Blat| subdirectory in the Biopython distribution:
%doctest ../Tests/Blat lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("dna_rna.bb", "bigbed")
>>> len(alignments)
4
>>> print(alignments.declaration)  # doctest: +NORMALIZE_WHITESPACE
table bed
"Browser Extensible Data"
(
   string          chrom;          "Reference sequence chromosome or scaffold"
   uint            chromStart;     "Start position in chromosome"
   uint            chromEnd;       "End position in chromosome"
   string          name;           "Name of item."
   uint            score;          "Score (0-1000)"
   char[1]         strand;         "+ or - for strand"
   uint            thickStart;     "Start of where display should be thick (start codon)"
   uint            thickEnd;       "End of where display should be thick (stop codon)"
   uint            reserved;       "Used as itemRgb as of 2004-11-22"
   int             blockCount;     "Number of blocks"
   int[blockCount] blockSizes;     "Comma separated list of block sizes"
   int[blockCount] chromStarts;    "Start positions relative to chromStart"
)
<BLANKLINE>
\end{minted}
The \verb|declaration| contains the specification of the columns, in AutoSql format, that was used to create the bigBed file.
Target sequences (typically, the chromosomes against which the sequences were aligned) are stored in the \verb|targets| attribute. In the bigBed format, only the identifier and the size of each target is stored. In this example, there is only a single chromosome:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.targets
[SeqRecord(seq=Seq(None, length=198295559), id='chr3', name='<unknown name>', description='<unknown description>', dbxrefs=[])]
\end{minted}
Let's look at the individual alignments. The alignment information is stored in the same way as for a BED file (see section \ref{subsec:align_bed}):
%cont-doctest
\begin{minted}{pycon}
>>> alignment = next(alignments)
>>> alignment.target.id
'chr3'
>>> alignment.query.id
'NR_046654.1'
>>> alignment.coordinates
array([[42530895, 42530958, 42532020, 42532095, 42532563, 42532606],
       [     181,      118,      118,       43,       43,        0]])
>>> alignment.thickStart
42530895
>>> alignment.thickEnd
42532606
>>> print(alignment)  # doctest: +ELLIPSIS
chr3       42530895 ????????????????????????????????????????????????????????????
                  0 ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
NR_046654       181 ????????????????????????????????????????????????????????????
<BLANKLINE>
chr3       42530955 ????????????????????????????????????????????????????????????
                 60 |||---------------------------------------------------------
NR_046654       121 ???---------------------------------------------------------
...
chr3       42532515 ????????????????????????????????????????????????????????????
               1620 ------------------------------------------------||||||||||||
NR_046654        43 ------------------------------------------------????????????
<BLANKLINE>
chr3       42532575 ??????????????????????????????? 42532606
               1680 |||||||||||||||||||||||||||||||     1711
NR_046654        31 ???????????????????????????????        0
<BLANKLINE>
\end{minted}
The default bigBed format does not store the sequence contents of the target and query. If these are available elsewhere (for example, a Fasta file), you can set \verb|alignment.target.seq| and \verb|alignment.query.seq| to show the sequence contents when printing the alignment, or to write the alignment in formats that require the sequence contents (such as Clustal, see section~\ref{subsec:align_clustal}). The test script \verb|test_Align_bigbed.py| in the \verb|Tests| subdirectory in the Biopython distribution gives some examples on how to do that.

Now let's see how to search for a sequence region. These are the sequences stored in the bigBed file, printed in BED format (see section \ref{subsec:align_bed}):
%cont-doctest
\begin{minted}{pycon}
>>> alignments.rewind()
>>> for alignment in alignments:
...     print(format(alignment, "bed"))  # doctest: +NORMALIZE_WHITESPACE
...
chr3	42530895	42532606	NR_046654.1	1000	-	42530895	42532606	0	3	63,75,43,	0,1125,1668,
<BLANKLINE>
chr3	42530895	42532606	NR_046654.1_modified	978	-	42530895	42532606	0	5	27,36,17,56,43,	0,27,1125,1144,1668,
<BLANKLINE>
chr3	48663767	48669174	NR_111921.1	1000	+	48663767	48669174	0	3	46,82,76,	0,1873,5331,
<BLANKLINE>
chr3	48663767	48669174	NR_111921.1_modified	972	+	48663767	48669174	0	5	28,17,76,6,76,	0,29,1873,1949,5331,
<BLANKLINE>
\end{minted}

Use the \verb|search| method on the \verb|alignments| object to find regions on chr3 between positions 48000000 and 49000000. This method returns an iterator:
%cont-doctest
\begin{minted}{pycon}
>>> selected_alignments = alignments.search("chr3", 48000000, 49000000)
>>> for alignment in selected_alignments:
...     print(alignment.query.id)
...
NR_111921.1
NR_111921.1_modified
\end{minted}
The chromosome name may be \verb|None| to include all chromosomes, and the start and end positions may be \verb|None| to start searching from position 0 or to continue searching until the end of the chromosome, respectively.

Writing alignments in the bigBed format is as easy as calling \verb|Bio.Align.write|:
\begin{minted}{pycon}
>>> Align.write(alignments, "output.bb", "bigbed")
\end{minted}
You can specify the number of BED fields to be included in the bigBed file. For example, to write a BED6 file, use
\begin{minted}{pycon}
>>> Align.write(alignments, "output.bb", "bigbed", bedN=6)
\end{minted}
Same as for \verb|bedToBigBed|, you can include additional columns in the bigBed output. Suppose the file \verb|bedExample2.as| (available in the \verb|Tests/Blat| subdirectory of the Biopython distribution) stores the declaration of the included BED fields in AutoSql format. We can read this declaration as follows:
%cont-doctest
\begin{minted}{pycon}
>>> from Bio.Align import bigbed
>>> with open("bedExample2.as") as stream:
...     autosql_data = stream.read()
...
>>> declaration = bigbed.AutoSQLTable.from_string(autosql_data)
>>> type(declaration)
<class 'Bio.Align.bigbed.AutoSQLTable'>
>>> print(declaration)
table hg18KGchr7
"UCSC Genes for chr7 with color plus GeneSymbol and SwissProtID"
(
   string  chrom;         "Reference sequence chromosome or scaffold"
   uint    chromStart;    "Start position of feature on chromosome"
   uint    chromEnd;      "End position of feature on chromosome"
   string  name;          "Name of gene"
   uint    score;         "Score"
   char[1] strand;        "+ or - for strand"
   uint    thickStart;    "Coding region start"
   uint    thickEnd;      "Coding region end"
   uint    reserved;      "Green on + strand, Red on - strand"
   string  geneSymbol;    "Gene Symbol"
   string  spID;          "SWISS-PROT protein Accession number"
)
<BLANKLINE>
\end{minted}
Now we can write a bigBed file with the 9 BED fields plus the additional fields \verb|geneSymbol| and \verb|spID| by calling
\begin{minted}{pycon}
>>> Align.write(
...     alignments,
...     "output.bb",
...     "bigbed",
...     bedN=9,
...     declaration=declaration,
...     extraIndex=["name", "geneSymbol"],
... )
\end{minted}
Here, we also requested to include additional indices on the \verb|name| and \verb|geneSymbol| in the bigBed file. \verb|Align.write| expects to find the keys \verb|geneSymbol| and \verb|spID| in the \verb|alignment.annotations| dictionary.
 Please refer to the test script \verb|test_Align_bigbed.py| in the \verb|Tests| subdirectory in the Biopython distribution for more examples of writing alignment files in the bigBed format.


\subsection{Pattern Space Layout (PSL)}
\label{subsec:align_psl}

PSL (Pattern Space Layout) files are are generated by the BLAST-Like Alignment Tool BLAT \cite{kent2002}. Like BED files (see section~\ref{subsec:align_bed}), PSL files are typically used to store alignments of transcripts to genomes.
This is an example of a short BLAT file (available as \verb|dna_rna.psl| in the \verb|Tests/Blat| subdirectory of the Biopython distribution), with the standard PSL header consisting of 5 lines:
\begin{minted}{text}
psLayout version 3

match	mis- 	rep. 	N's	Q gap	Q gap	T gap	T gap	strand	Q        	Q   	Q    	Q  	T        	T   	T    	T  	block	blockSizes 	qStarts	 tStarts
     	match	match	   	count	bases	count	bases	      	name     	size	start	end	name     	size	start	end	count
---------------------------------------------------------------------------------------------------------------------------------------------------------------
165	0	39	0	0	0	2	5203	+	NR_111921.1	216	0	204	chr3	198295559	48663767	48669174	3	46,82,76,	0,46,128,	48663767,48665640,48669098,
175	0	6	0	0	0	2	1530	-	NR_046654.1	181	0	181	chr3	198295559	42530895	42532606	3	63,75,43,	0,63,138,	42530895,42532020,42532563,
162	2	39	0	1	2	3	5204	+	NR_111921.1_modified	220	3	208	chr3	198295559	48663767	48669174	5	28,17,76,6,76,	3,31,48,126,132,	48663767,48663796,48665640,48665716,48669098,
172	1	6	0	1	3	3	1532	-	NR_046654.1_modified	190	3	185	chr3	198295559	42530895	42532606	5	27,36,17,56,43,	5,35,71,88,144,	42530895,42530922,42532020,42532039,42532563,
\end{minted}
To parse this file, use
%doctest ../Tests/Blat lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("dna_rna.psl", "psl")
>>> alignments.metadata
{'psLayout version': '3'}
\end{minted}
Iterate over the alignments to get one \verb|Alignment| object for each line:
%cont-doctest
\begin{minted}{pycon}
>>> for alignment in alignments:
...     print(alignment.target.id, alignment.query.id)
...
chr3 NR_046654.1
chr3 NR_046654.1_modified
chr3 NR_111921.1
chr3 NR_111921.1_modified
\end{minted}
Let's look at the last alignment in more detail. The first four columns in the PSL file show the number of matches, the number of mismatches, the number of nucleotides aligned to repeat regions, and the number of nucleotides aligned to N (unknown) characters. These values are stored as attributes to the \verb|Alignment| object:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.matches
162
>>> alignment.misMatches
2
>>> alignment.repMatches
39
>>> alignment.nCount
0
\end{minted}
As the sequence data of the target and query are not stored explicitly in the PSL file, the sequence content of \verb|alignment.target| and \verb|alignment.query| is undefined. However, their sequence lengths are known:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.target  # doctest: +ELLIPSIS
SeqRecord(seq=Seq(None, length=198295559), id='chr3', ...)
>>> alignment.query  # doctest: +ELLIPSIS
SeqRecord(seq=Seq(None, length=220), id='NR_111921.1_modified', ...)
\end{minted}
We can print the alignment in BED or PSL format:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "bed"))  # doctest: +NORMALIZE_WHITESPACE
chr3	48663767	48669174	NR_111921.1_modified	0	+	48663767	48669174	0	5	28,17,76,6,76,	0,29,1873,1949,5331,
<BLANKLINE>
>>> print(format(alignment, "psl"))  # doctest: +NORMALIZE_WHITESPACE
162	2	39	0	1	2	3	5204	+	NR_111921.1_modified	220	3	208	chr3	198295559	48663767	48669174	5	28,17,76,6,76,	3,31,48,126,132,	48663767,48663796,48665640,48665716,48669098,
<BLANKLINE>
\end{minted}
Here, the number of matches, mismatches, repeat region matches, and matches to unknown nucleotides were taken from the corresponding attributes of the \verb|Alignment| object. If these attributes are not available, for example if the alignment did not come from a PSL file, then these numbers are calculated using the sequence contents, if available.
Repeat regions in the target sequence are indicated by masking the sequence as lower-case or upper-case characters, as defined by the following values for the \verb+mask+ keyword argument:
\begin{itemize}
\item \verb+False+ (default): Do not count matches to masked sequences separately;
\item \verb+"lower"+: Count and report matches to lower-case characters as matches to repeat regions;
\item \verb+"upper"+: Count and report matches to upper-case characters as matches to repeat regions;
\end{itemize}
The character used for unknown nucleotides is defined by the \verb+wildcard+ argument. For consistency with BLAT, the wildcard character is \verb+"N"+ by default. Use \verb+wildcard=None+ if you don't want to count matches to any unknown nucleotides separately.
%doctest . lib:numpy
\begin{minted}{pycon}
>>> import numpy
>>> from Bio import Align
>>> query = "GGTGGGGG"
>>> target = "AAAAAAAggggGGNGAAAAA"
>>> coordinates = numpy.array([[0, 7, 15, 20], [0, 0, 8, 8]])
>>> alignment = Align.Alignment([target, query], coordinates)
>>> print(alignment)
target            0 AAAAAAAggggGGNGAAAAA 20
                  0 -------....||.|----- 20
query             0 -------GGTGGGGG-----  8
<BLANKLINE>
>>> line = alignment.format("psl")
>>> print(line)  # doctest: +NORMALIZE_WHITESPACE
6   1   0   1   0   0   0   0   +   query   8   0   8   target   20   7   15   1   8,   0,   7,
>>> line = alignment.format("psl", mask="lower")
>>> print(line)  # doctest: +NORMALIZE_WHITESPACE
3   1   3   1   0   0   0   0   +   query   8   0   8   target   20   7   15   1   8,   0,   7,
>>> line = alignment.format("psl", mask="lower", wildcard=None)
>>> print(line)  # doctest: +NORMALIZE_WHITESPACE
3   2   3   0   0   0   0   0   +   query   8   0   8   target   20   7   15   1   8,   0,   7,
\end{minted}
The same arguments can be used when writing alignments to an output file in PSL format using \verb|Bio.Align.write|. This function has an additional keyword \verb|header| (\verb|True| by default) specifying if the PSL header should be written.

In addition to the \verb+format+ method, you can use Python's built-in \verb+format+ function:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "psl"))  # doctest: +NORMALIZE_WHITESPACE
6   1   0   1   0   0   0   0   +   query   8   0   8   target   20   7   15   1   8,   0,   7,
\end{minted}
allowing \verb+Alignment+ objects to be used in formatted (f-) strings in Python:
\begin{minted}{pycon}
>>> line = f"The alignment in PSL format is '{alignment:psl}'."
>>> print(line)  # doctest: +NORMALIZE_WHITESPACE
The alignment in PSL format is '6   1   0   1   0   0   0   0   +   query   8   0   8   target   20   7   15   1   8,   0,   7,
'
\end{minted}
Note that optional keyword arguments cannot be used with the \verb+format+ function or with formatted strings.

\subsection{bigPsl}
\label{subsec:align_bigpsl}

A bigPsl file is a bigBed file with a BED12+13 format consisting of the 12
predefined BED fields and 13 custom fields defined in the AutoSql file
\href{https://genome.ucsc.edu/goldenPath/help/bigPsl.html}{bigPsl.as} provided by UCSC, creating an indexed binary version of a PSL file (see section~\ref{subsec:align_psl}). To create a bigPsl file, you can either use the \verb+pslToBigPsl+ and \verb+bedToBigBed+ programs from UCSC. or you can use Biopython by calling the \verb|Bio.Align.write| function with \verb|fmt="bigpsl"|. While the two methods should result in identical bigPsl files, the UCSC tools are much faster and may be more reliable, as it is the gold standard. As bigPsl files are bigBed files, they come with a built-in index, allowing you to quickly search a specific genomic region.

As an example, let's parse the bigBed file \verb|dna_rna.psl.bb|, available in the \verb|Tests/Blat| subdirectory in the Biopython distribution. This file is the bigPsl equivalent of the bigBed file \verb|dna_rna.bb| (see section~\ref{subsec:align_bigbed}) and of the PSL file \verb|dna_rna.psl| (see section~\ref{subsec:align_psl}).
%doctest ../Tests/Blat lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("dna_rna.psl.bb", "bigpsl")
>>> len(alignments)
4
>>> print(alignments.declaration)  # doctest: +NORMALIZE_WHITESPACE
table bigPsl
"bigPsl pairwise alignment"
(
   string          chrom;           "Reference sequence chromosome or scaffold"
   uint            chromStart;      "Start position in chromosome"
   uint            chromEnd;        "End position in chromosome"
   string          name;            "Name or ID of item, ideally both human readable and unique"
   uint            score;           "Score (0-1000)"
   char[1]         strand;          "+ or - indicates whether the query aligns to the + or - strand on the reference"
   uint            thickStart;      "Start of where display should be thick (start codon)"
   uint            thickEnd;        "End of where display should be thick (stop codon)"
   uint            reserved;        "RGB value (use R,G,B string in input file)"
   int             blockCount;      "Number of blocks"
   int[blockCount] blockSizes;      "Comma separated list of block sizes"
   int[blockCount] chromStarts;     "Start positions relative to chromStart"
   uint            oChromStart;     "Start position in other chromosome"
   uint            oChromEnd;       "End position in other chromosome"
   char[1]         oStrand;         "+ or -, - means that psl was reversed into BED-compatible coordinates"
   uint            oChromSize;      "Size of other chromosome."
   int[blockCount] oChromStarts;    "Start positions relative to oChromStart or from oChromStart+oChromSize depending on strand"
   lstring         oSequence;       "Sequence on other chrom (or edit list, or empty)"
   string          oCDS;            "CDS in NCBI format"
   uint            chromSize;       "Size of target chromosome"
   uint            match;           "Number of bases matched."
   uint            misMatch;        "Number of bases that don't match"
   uint            repMatch;        "Number of bases that match but are part of repeats"
   uint            nCount;          "Number of 'N' bases"
   uint            seqType;         "0=empty, 1=nucleotide, 2=amino_acid"
)
<BLANKLINE>
\end{minted}
The declaration contains the specification of the columns as defined by the \verb|bigPsl.as| AutoSql file from UCSC. Target sequences (typically, the chromosomes against which the sequences were aligned) are stored in the \verb|targets| attribute. In the bigBed format, only the identifier and the size of each target is stored. In this example, there is only a single chromosome: 
%cont-doctest
\begin{minted}{pycon}
>>> alignments.targets
[SeqRecord(seq=Seq(None, length=198295559), id='chr3', name='<unknown name>', description='<unknown description>', dbxrefs=[])]
\end{minted}
Iterating over the alignments gives one Alignment object for each line: 
%cont-doctest
\begin{minted}{pycon}
>>> for alignment in alignments:
...     print(alignment.target.id, alignment.query.id)
...
chr3 NR_046654.1
chr3 NR_046654.1_modified
chr3 NR_111921.1
chr3 NR_111921.1_modified
\end{minted}
Let's look at the individual alignments. The alignment information is stored in the same way as for the corresponding PSL file (see section~\ref{subsec:align_psl}):
%cont-doctest
\begin{minted}{pycon}
>>> alignment.coordinates
array([[48663767, 48663795, 48663796, 48663813, 48665640, 48665716,
        48665716, 48665722, 48669098, 48669174],
       [       3,       31,       31,       48,       48,      124,
             126,      132,      132,      208]])
>>> alignment.thickStart
48663767
>>> alignment.thickEnd
48669174
>>> alignment.matches
162
>>> alignment.misMatches
2
>>> alignment.repMatches
39
>>> alignment.nCount
0
\end{minted}
We can print the alignment in BED or PSL format:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "bed"))  # doctest: +NORMALIZE_WHITESPACE
chr3	48663767	48669174	NR_111921.1_modified	1000	+	48663767	48669174	0	5	28,17,76,6,76,	0,29,1873,1949,5331,
<BLANKLINE>
>>> print(format(alignment, "psl"))  # doctest: +NORMALIZE_WHITESPACE
162	2	39	0	1	2	3	5204	+	NR_111921.1_modified	220	3	208	chr3	198295559	48663767	48669174	5	28,17,76,6,76,	3,31,48,126,132,	48663767,48663796,48665640,48665716,48669098,
<BLANKLINE>
\end{minted}

As a bigPsl file is a special case of a bigBed file, you can use the \verb|search| method on the alignments object to find alignments to specific genomic regions. For example, we can look for regions on chr3 between positions 48000000 and 49000000:
%cont-doctest
\begin{minted}{pycon}
>>> selected_alignments = alignments.search("chr3", 48000000, 49000000)
>>> for alignment in selected_alignments:
...     print(alignment.query.id)
...
NR_111921.1
NR_111921.1_modified
\end{minted}
The chromosome name may be \verb|None| to include all chromosomes, and the start and end positions may be \verb|None| to start searching from position 0 or to continue searching until the end of the chromosome, respectively.

To write a bigPsl file with Biopython, use \verb|Bio.Align.write(alignments, "myfilename.bb", fmt="bigpsl")|, where \verb|myfilename.bb| is the name of the output bigPsl file. Alternatively, you can use a (binary) stream for output. Additional options are
\begin{itemize}
\item \verb|compress|: If \verb|True| (default), compress data using zlib; if \verb|False|, do not compress data.
\item \verb|extraIndex|: List of strings with the names of extra columns to be indexed.
\item \verb|cds|: If \verb|True|, look for a query feature of type CDS and write it in NCBI style in the PSL file (default: \verb|False|).
\item \verb|fa|: If \verb|True|, include the query sequence in the PSL file (default: \verb|False|).
\item \verb|mask|: Specify if repeat regions in the target sequence are masked and should be reported in the \verb|repMatches| field instead of in the \verb|matches| field.  Acceptable values are
\begin{itemize}
\item \verb|None|: no masking (default);
\item \verb|"lower"|: masking by lower-case characters;
\item \verb|"upper"|: masking by upper-case characters.
\end{itemize}
\item \verb|wildcard|: Report alignments to the wildcard character (representing unknown nucleotides) in the target or query sequence in the \verb|nCount| field instead of in the \verb|matches|, \verb|misMatches|, or \verb|repMatches| fields.  Default value is \verb|"N"|.
\end{itemize}
See section~\ref{subsec:align_psl} for an explanation on how the number of matches, mismatches, repeat region matches, and matches to unknown nucleotides are obtained.


\subsection{Multiple Alignment Format (MAF)}
\label{subsec:align_maf}

MAF (Multiple Alignment Format) files store a series of multiple sequence alignments in a human-readable format. MAF files are typically used to store alignment
s of genomes to each other. The file \verb|ucsc_test.maf| in the \verb|Tests/MAF| subdirectory of the Biopython distribution is an example of a simple MAF file:
\begin{minted}{text}
track name=euArc visibility=pack mafDot=off frames="multiz28wayFrames" speciesOrder="hg16 panTro1 baboon mm4 rn3" description="A sample alignment"
##maf version=1 scoring=tba.v8
# tba.v8 (((human chimp) baboon) (mouse rat))
# multiz.v7
# maf_project.v5 _tba_right.maf3 mouse _tba_C
# single_cov2.v4 single_cov2 /dev/stdin

a score=23262.0
s hg16.chr7    27578828 38 + 158545518 AAA-GGGAATGTTAACCAAATGA---ATTGTCTCTTACGGTG
s panTro1.chr6 28741140 38 + 161576975 AAA-GGGAATGTTAACCAAATGA---ATTGTCTCTTACGGTG
s baboon         116834 38 +   4622798 AAA-GGGAATGTTAACCAAATGA---GTTGTCTCTTATGGTG
s mm4.chr6     53215344 38 + 151104725 -AATGGGAATGTTAAGCAAACGA---ATTGTCTCTCAGTGTG
s rn3.chr4     81344243 40 + 187371129 -AA-GGGGATGCTAAGCCAATGAGTTGTTGTCTCTCAATGTG

a score=5062.0
s hg16.chr7    27699739 6 + 158545518 TAAAGA
s panTro1.chr6 28862317 6 + 161576975 TAAAGA
s baboon         241163 6 +   4622798 TAAAGA
s mm4.chr6     53303881 6 + 151104725 TAAAGA
s rn3.chr4     81444246 6 + 187371129 taagga

a score=6636.0
s hg16.chr7    27707221 13 + 158545518 gcagctgaaaaca
s panTro1.chr6 28869787 13 + 161576975 gcagctgaaaaca
s baboon         249182 13 +   4622798 gcagctgaaaaca
s mm4.chr6     53310102 13 + 151104725 ACAGCTGAAAATA

\end{minted}
To parse this file, use
%doctest ../Tests/MAF lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("ucsc_test.maf", "maf")
\end{minted}
Information shown in the file header (the track line and subsequent lines starting with "\verb|#|")) is stored in the \verb|metadata| attribute of the \verb|alignments| object:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.metadata  # doctest: +NORMALIZE_WHITESPACE
{'name': 'euArc',
 'visibility': 'pack',
 'mafDot': 'off',
 'frames': 'multiz28wayFrames',
 'speciesOrder': ['hg16', 'panTro1', 'baboon', 'mm4', 'rn3'],
 'description': 'A sample alignment',
 'MAF Version': '1',
 'Scoring': 'tba.v8',
 'Comments': ['tba.v8 (((human chimp) baboon) (mouse rat))',
              'multiz.v7',
              'maf_project.v5 _tba_right.maf3 mouse _tba_C',
              'single_cov2.v4 single_cov2 /dev/stdin']}
\end{minted}
By iterating over the \verb|alignments| we obtain one \verb|Alignment| object for each alignment block in the MAF file:
%cont-doctest
\begin{minted}{pycon}
>>> alignment = next(alignments)
>>> alignment.score
23262.0
>>> {seq.id: len(seq) for seq in alignment.sequences}  # doctest: +NORMALIZE_WHITESPACE
{'hg16.chr7': 158545518,
 'panTro1.chr6': 161576975,
 'baboon': 4622798,
 'mm4.chr6': 151104725,
 'rn3.chr4': 187371129}
>>> alignment.coordinates  # doctest: +NORMALIZE_WHITESPACE
array([[27578828, 27578829, 27578831, 27578831, 27578850, 27578850, 27578866],
       [28741140, 28741141, 28741143, 28741143, 28741162, 28741162, 28741178],
       [  116834,   116835,   116837,   116837,   116856,   116856, 116872],
       [53215344, 53215344, 53215346, 53215347, 53215366, 53215366, 53215382],
       [81344243, 81344243, 81344245, 81344245, 81344264, 81344267, 81344283]])
>>> print(alignment)
hg16.chr7  27578828 AAA-GGGAATGTTAACCAAATGA---ATTGTCTCTTACGGTG 27578866
panTro1.c  28741140 AAA-GGGAATGTTAACCAAATGA---ATTGTCTCTTACGGTG 28741178
baboon       116834 AAA-GGGAATGTTAACCAAATGA---GTTGTCTCTTATGGTG   116872
mm4.chr6   53215344 -AATGGGAATGTTAAGCAAACGA---ATTGTCTCTCAGTGTG 53215382
rn3.chr4   81344243 -AA-GGGGATGCTAAGCCAATGAGTTGTTGTCTCTCAATGTG 81344283
<BLANKLINE>
>>> print(format(alignment, "phylip"))
5 42
hg16.chr7 AAA-GGGAATGTTAACCAAATGA---ATTGTCTCTTACGGTG
panTro1.chAAA-GGGAATGTTAACCAAATGA---ATTGTCTCTTACGGTG
baboon    AAA-GGGAATGTTAACCAAATGA---GTTGTCTCTTATGGTG
mm4.chr6  -AATGGGAATGTTAAGCAAACGA---ATTGTCTCTCAGTGTG
rn3.chr4  -AA-GGGGATGCTAAGCCAATGAGTTGTTGTCTCTCAATGTG
<BLANKLINE>
\end{minted}
In addition to the "\verb|a|" (alignment block) and "\verb|s|" (sequence) lines, MAF files may contain "\verb|i|" lines with information about the genome sequence before and after this block, "\verb|e|" lines with information about empty parts of the alignment, and "\verb|q|" lines showing the quality of each aligned base. This is an example of an alignment block including such lines:
\begin{minted}{text}
a score=19159.000000
s mm9.chr10                         3014644 45 + 129993255 CCTGTACC---CTTTGGTGAGAATTTTTGTTTCAGTGTTAAAAGTTTG
s hg18.chr6                        15870786 46 - 170899992 CCTATACCTTTCTTTTATGAGAA-TTTTGTTTTAATCCTAAAC-TTTT
i hg18.chr6                        I 9085 C 0
s panTro2.chr6                     16389355 46 - 173908612 CCTATACCTTTCTTTTATGAGAA-TTTTGTTTTAATCCTAAAC-TTTT
q panTro2.chr6                                             99999999999999999999999-9999999999999999999-9999
i panTro2.chr6                     I 9106 C 0
s calJac1.Contig6394                   6182 46 +    133105 CCTATACCTTTCTTTCATGAGAA-TTTTGTTTGAATCCTAAAC-TTTT
i calJac1.Contig6394               N 0 C 0
s loxAfr1.scaffold_75566               1167 34 -     10574 ------------TTTGGTTAGAA-TTATGCTTTAATTCAAAAC-TTCC
q loxAfr1.scaffold_75566                                   ------------99999699899-9999999999999869998-9997
i loxAfr1.scaffold_75566           N 0 C 0
e tupBel1.scaffold_114895.1-498454   167376 4145 -    498454 I
e echTel1.scaffold_288249             87661 7564 +    100002 I
e otoGar1.scaffold_334.1-359464      181217 2931 -    359464 I
e ponAbe2.chr6                     16161448 8044 - 174210431 I
\end{minted}
This is the 10th alignment block in the file \verb|ucsc_mm9_chr10.maf| (available in the \verb|Tests/MAF| subdirectory of the Biopython distribution):
%doctest ../Tests/MAF lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("ucsc_mm9_chr10.maf", "maf")
>>> for i in range(10):
...     alignment = next(alignments)
...
>>> alignment.score
19159.0
>>> print(alignment)
mm9.chr10   3014644 CCTGTACC---CTTTGGTGAGAATTTTTGTTTCAGTGTTAAAAGTTTG   3014689
hg18.chr6 155029206 CCTATACCTTTCTTTTATGAGAA-TTTTGTTTTAATCCTAAAC-TTTT 155029160
panTro2.c 157519257 CCTATACCTTTCTTTTATGAGAA-TTTTGTTTTAATCCTAAAC-TTTT 157519211
calJac1.C      6182 CCTATACCTTTCTTTCATGAGAA-TTTTGTTTGAATCCTAAAC-TTTT      6228
loxAfr1.s      9407 ------------TTTGGTTAGAA-TTATGCTTTAATTCAAAAC-TTCC      9373
<BLANKLINE>
\end{minted}

The "\verb|i|" lines show the relationship between the sequence in the current alignment block to the ones in the preceding and subsequent alignment block. This information is stored in the \verb|annotations| attribute of the corresponding sequence:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.sequences[0].annotations
{}
>>> alignment.sequences[1].annotations
{'leftStatus': 'I', 'leftCount': 9085, 'rightStatus': 'C', 'rightCount': 0}
\end{minted}
showing that there are 9085 bases inserted ("\verb|I|") between this block and the preceding one, while the block is contiguous ("\verb|C|") with the subsequent one.  See the \href{https://genome.ucsc.edu/FAQ/FAQformat.html#format5}{UCSC documentation} for the full description of these fields and status characters.

The "\verb|q|" lines show the sequence quality, which is stored under the "\verb|quality|" dictionary key of the\verb|annotations| attribute of the corresponding sequence:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.sequences[2].annotations["quality"]
'9999999999999999999999999999999999999999999999'
>>> alignment.sequences[4].annotations["quality"]
'9999969989999999999999998699989997'
\end{minted}

The "\verb|e|" lines show information about species with a contiguous sequence before and after this alignment bloack, but with no aligning nucleotides in this alignment block. This is stored under the "\verb|empty|" key of the \verb|alignment.annotations| dictionary:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.annotations["empty"]  # doctest: +NORMALIZE_WHITESPACE
[(SeqRecord(seq=Seq(None, length=498454), id='tupBel1.scaffold_114895.1-498454', name='', description='', dbxrefs=[]), (331078, 326933), 'I'),
 (SeqRecord(seq=Seq(None, length=100002), id='echTel1.scaffold_288249', name='', description='', dbxrefs=[]), (87661, 95225), 'I'),
 (SeqRecord(seq=Seq(None, length=359464), id='otoGar1.scaffold_334.1-359464', name='', description='', dbxrefs=[]), (178247, 175316), 'I'),
 (SeqRecord(seq=Seq(None, length=174210431), id='ponAbe2.chr6', name='', description='', dbxrefs=[]), (158048983, 158040939), 'I')]
\end{minted}
This shows for example that there were non-aligning bases inserted ("\verb|I|") from position 158040939 to 158048983 on the opposite strand of the \verb|ponAbe2.chr6| genomic sequence.
Again, see the \href{https://genome.ucsc.edu/FAQ/FAQformat.html#format5}{UCSC documentation} for the full definition of "\verb|e|" lines.

To print an alignment in MAF format, you can use Python's built-in \verb|format| function:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "MAF"))
a score=19159.000000
s mm9.chr10                         3014644   45 + 129993255 CCTGTACC---CTTTGGTGAGAATTTTTGTTTCAGTGTTAAAAGTTTG
s hg18.chr6                        15870786   46 - 170899992 CCTATACCTTTCTTTTATGAGAA-TTTTGTTTTAATCCTAAAC-TTTT
i hg18.chr6                        I 9085 C 0
s panTro2.chr6                     16389355   46 - 173908612 CCTATACCTTTCTTTTATGAGAA-TTTTGTTTTAATCCTAAAC-TTTT
q panTro2.chr6                                               99999999999999999999999-9999999999999999999-9999
i panTro2.chr6                     I 9106 C 0
s calJac1.Contig6394                   6182   46 +    133105 CCTATACCTTTCTTTCATGAGAA-TTTTGTTTGAATCCTAAAC-TTTT
i calJac1.Contig6394               N 0 C 0
s loxAfr1.scaffold_75566               1167   34 -     10574 ------------TTTGGTTAGAA-TTATGCTTTAATTCAAAAC-TTCC
q loxAfr1.scaffold_75566                                     ------------99999699899-9999999999999869998-9997
i loxAfr1.scaffold_75566           N 0 C 0
e tupBel1.scaffold_114895.1-498454   167376 4145 -    498454 I
e echTel1.scaffold_288249             87661 7564 +    100002 I
e otoGar1.scaffold_334.1-359464      181217 2931 -    359464 I
e ponAbe2.chr6                     16161448 8044 - 174210431 I
<BLANKLINE>
<BLANKLINE>
\end{minted}
To write a complete MAF file, use \verb|Bio.Align.write(alignments, "myfilename.maf", fmt="maf")|, where \verb|myfilename.maf| is the name of the output MAF file. Alternatively, you can use a (text) stream for output. File header information will be taken from the \verb|metadata| attribute of the \verb|alignments| object. If you are creating the alignments from scratch, you can use the \verb|Alignments| (plural) class to create a list-like \verb|alignments| object (see Section~\ref{sec:alignments}) and give it a \verb|metadata| attribute.

\subsection{bigMaf}
\label{subsec:align_bigmaf}

A bigMaf file is a bigBed file with a BED3+1 format consisting of the 3 required BED fields plus a custom field that stores a MAF alignment block as a string, crearing an indexed binary version of a MAF file (see section~\ref{subsec:align_bigmaf}). The associated AutoSql file \href{https://genome.ucsc.edu/goldenPath/help/examples/bigMaf.as}{bigMaf.as} is provided by UCSC.
To create a bigMaf file, you can either use the \verb|mafToBigMaf| and \verb|bedToBigBed| programs from UCSC. or you can use Biopython by calling the Bio.Align.write function with \verb|fmt="bigmaf"|. While the two methods should result in identical bigMaf files, the UCSC tools are much faster and may be more reliable, as it is the gold standard. As bigMaf files are bigBed files, they come with a built-in index, allowing you to quickly search a specific region of the reference genome.

The file \verb|ucsc_test.bb| in the \verb|Tests/MAF| subdirectory of the Biopython distribution is an example of a bigMaf file. This file is equivalent to the MAF file \verb|ucsc_test.maf| (see section~\ref{subsec:align_maf}).
To parse this file, use
%doctest ../Tests/MAF lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("ucsc_test.bb", "bigmaf")
>>> len(alignments)
3
>>> print(alignments.declaration)  # doctest: +NORMALIZE_WHITESPACE
table bedMaf
"Bed3 with MAF block"
(
   string  chrom;         "Reference sequence chromosome or scaffold"
   uint    chromStart;    "Start position in chromosome"
   uint    chromEnd;      "End position in chromosome"
   lstring mafBlock;      "MAF block"
)
<BLANKLINE>
\end{minted}
The declaration contains the specification of the columns as defined by the bigMaf.as AutoSql file from UCSC.

The bigMaf file does not store the header information found in the MAF file, but it does define a reference genome. The corresponding \verb|SeqRecord| is stored in the \verb|targets| attribute of the \verb|alignments| object:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.reference
'hg16'
>>> alignments.targets  # doctest: +ELLIPSIS
[SeqRecord(seq=Seq(None, length=158545518), id='hg16.chr7', ...)]
\end{minted}

By iterating over the \verb|alignments| we obtain one \verb|Alignment| object for each alignment block in the bigMaf file:
%cont-doctest
\begin{minted}{pycon}
>>> alignment = next(alignments)
>>> alignment.score
23262.0
>>> {seq.id: len(seq) for seq in alignment.sequences}  # doctest: +NORMALIZE_WHITESPACE
{'hg16.chr7': 158545518,
 'panTro1.chr6': 161576975,
 'baboon': 4622798,
 'mm4.chr6': 151104725,
 'rn3.chr4': 187371129}
>>> alignment.coordinates  # doctest: +NORMALIZE_WHITESPACE
array([[27578828, 27578829, 27578831, 27578831, 27578850, 27578850, 27578866],
       [28741140, 28741141, 28741143, 28741143, 28741162, 28741162, 28741178],
       [  116834,   116835,   116837,   116837,   116856,   116856, 116872],
       [53215344, 53215344, 53215346, 53215347, 53215366, 53215366, 53215382],
       [81344243, 81344243, 81344245, 81344245, 81344264, 81344267, 81344283]])
>>> print(alignment)
hg16.chr7  27578828 AAA-GGGAATGTTAACCAAATGA---ATTGTCTCTTACGGTG 27578866
panTro1.c  28741140 AAA-GGGAATGTTAACCAAATGA---ATTGTCTCTTACGGTG 28741178
baboon       116834 AAA-GGGAATGTTAACCAAATGA---GTTGTCTCTTATGGTG   116872
mm4.chr6   53215344 -AATGGGAATGTTAAGCAAACGA---ATTGTCTCTCAGTGTG 53215382
rn3.chr4   81344243 -AA-GGGGATGCTAAGCCAATGAGTTGTTGTCTCTCAATGTG 81344283
<BLANKLINE>
>>> print(format(alignment, "phylip"))
5 42
hg16.chr7 AAA-GGGAATGTTAACCAAATGA---ATTGTCTCTTACGGTG
panTro1.chAAA-GGGAATGTTAACCAAATGA---ATTGTCTCTTACGGTG
baboon    AAA-GGGAATGTTAACCAAATGA---GTTGTCTCTTATGGTG
mm4.chr6  -AATGGGAATGTTAAGCAAACGA---ATTGTCTCTCAGTGTG
rn3.chr4  -AA-GGGGATGCTAAGCCAATGAGTTGTTGTCTCTCAATGTG
<BLANKLINE>
\end{minted}
Information in the "\verb|i|", "\verb|e|", and "\verb|q|" lines is stored in the same way as in the corresponding MAF file (see section~\ref{subsec:align_maf}):
%doctest ../Tests/MAF lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("ucsc_mm9_chr10.bb", "bigmaf")
>>> for i in range(10):
...     alignment = next(alignments)
...
>>> alignment.score
19159.0
>>> print(alignment)
mm9.chr10   3014644 CCTGTACC---CTTTGGTGAGAATTTTTGTTTCAGTGTTAAAAGTTTG   3014689
hg18.chr6 155029206 CCTATACCTTTCTTTTATGAGAA-TTTTGTTTTAATCCTAAAC-TTTT 155029160
panTro2.c 157519257 CCTATACCTTTCTTTTATGAGAA-TTTTGTTTTAATCCTAAAC-TTTT 157519211
calJac1.C      6182 CCTATACCTTTCTTTCATGAGAA-TTTTGTTTGAATCCTAAAC-TTTT      6228
loxAfr1.s      9407 ------------TTTGGTTAGAA-TTATGCTTTAATTCAAAAC-TTCC      9373
<BLANKLINE>
>>> print(format(alignment, "MAF"))
a score=19159.000000
s mm9.chr10                         3014644   45 + 129993255 CCTGTACC---CTTTGGTGAGAATTTTTGTTTCAGTGTTAAAAGTTTG
s hg18.chr6                        15870786   46 - 170899992 CCTATACCTTTCTTTTATGAGAA-TTTTGTTTTAATCCTAAAC-TTTT
i hg18.chr6                        I 9085 C 0
s panTro2.chr6                     16389355   46 - 173908612 CCTATACCTTTCTTTTATGAGAA-TTTTGTTTTAATCCTAAAC-TTTT
q panTro2.chr6                                               99999999999999999999999-9999999999999999999-9999
i panTro2.chr6                     I 9106 C 0
s calJac1.Contig6394                   6182   46 +    133105 CCTATACCTTTCTTTCATGAGAA-TTTTGTTTGAATCCTAAAC-TTTT
i calJac1.Contig6394               N 0 C 0
s loxAfr1.scaffold_75566               1167   34 -     10574 ------------TTTGGTTAGAA-TTATGCTTTAATTCAAAAC-TTCC
q loxAfr1.scaffold_75566                                     ------------99999699899-9999999999999869998-9997
i loxAfr1.scaffold_75566           N 0 C 0
e tupBel1.scaffold_114895.1-498454   167376 4145 -    498454 I
e echTel1.scaffold_288249             87661 7564 +    100002 I
e otoGar1.scaffold_334.1-359464      181217 2931 -    359464 I
e ponAbe2.chr6                     16161448 8044 - 174210431 I
<BLANKLINE>
<BLANKLINE>
>>> alignment.sequences[1].annotations
{'leftStatus': 'I', 'leftCount': 9085, 'rightStatus': 'C', 'rightCount': 0}
>>> alignment.sequences[2].annotations["quality"]
'9999999999999999999999999999999999999999999999'
>>> alignment.sequences[4].annotations["quality"]
'9999969989999999999999998699989997'
>>> alignment.annotations["empty"]  # doctest: +NORMALIZE_WHITESPACE
[(SeqRecord(seq=Seq(None, length=498454), id='tupBel1.scaffold_114895.1-498454', name='', description='', dbxrefs=[]), (331078, 326933), 'I'),
 (SeqRecord(seq=Seq(None, length=100002), id='echTel1.scaffold_288249', name='', description='', dbxrefs=[]), (87661, 95225), 'I'),
 (SeqRecord(seq=Seq(None, length=359464), id='otoGar1.scaffold_334.1-359464', name='', description='', dbxrefs=[]), (178247, 175316), 'I'),
 (SeqRecord(seq=Seq(None, length=174210431), id='ponAbe2.chr6', name='', description='', dbxrefs=[]), (158048983, 158040939), 'I')]
\end{minted}

To write a complete bigMaf file, use \verb|Bio.Align.write(alignments, "myfilename.bb", fmt="bigMaf")|, where \verb|myfilename.bb| is the name of the output bigMaf file. Alternatively, you can use a (binary) stream for output. If you are creating the alignments from scratch, you can use the \verb|Alignments| (plural) class to create a list-like \verb|alignments| object (see Section~\ref{sec:alignments}) and give it a \verb|targets| attribute. The latter must be a list of \verb|SeqRecord| objects for the chromosomes for the reference species in the order in which they appear in the alignments. Alternatively, you can use the \verb|targets| keyword argument when calling \verb|Bio.Align.write|. The \verb|id| of each \verb|SeqRecord| must be of the form \verb|reference.chromosome|, where \verb|reference| refers to the reference species. \verb|Bio.Align.write| has the additional keyword argument \verb|compress| (\verb|True| by default) specifying whether the data should be compressed using zlib.

As a bigMaf file is a special case of a bigBed file, you can use the \verb|search| method on the \verb|alignments| object to find alignments to specific regions of the reference species. For example, we can look for regions on chr10 between positions 3018000 and 3019000 on chromosome 10:

%cont-doctest
\begin{minted}{pycon}
>>> selected_alignments = alignments.search("mm9.chr10", 3018000, 3019000)
>>> for alignment in selected_alignments:
...     start, end = alignment.coordinates[0, 0], alignment.coordinates[0, -1]
...     print(start, end)
...
3017743 3018161
3018161 3018230
3018230 3018359
3018359 3018482
3018482 3018644
3018644 3018822
3018822 3018932
3018932 3019271
\end{minted}
The chromosome name may be \verb|None| to include all chromosomes, and the start and end positions may be \verb|None| to start searching from position 0 or to continue searching until the end of the chromosome, respectively. Note that we can search on genomic position for the reference species only.

\subsection{UCSC chain file format}
\label{subsec:align_chain}

Chain files describe a pairwise alignment between two nucleotide sequences, allowing gaps in both sequences. Only the length of each aligned subsequences and the gap lengths are stored in a chain file; the sequences themselves are not stored. Chain files are typically used to store alignments between two genome assembly versions, allowing alignments to one genome assembly version to be lifted over to the other genome assembly. This is an example of a chain file (available as \verb+psl_34_001.chain+ in the \verb+Tests/Blat+ subdirectory of the Biopython distribution):
\begin{minted}{text}
chain 16 chr4 191154276 + 61646095 61646111 hg18_dna 33 + 11 27 1
16
chain 33 chr1 249250621 + 10271783 10271816 hg18_dna 33 + 0 33 2
33
chain 17 chr2 243199373 + 53575980 53575997 hg18_dna 33 - 8 25 3
17
chain 35 chr9 141213431 + 85737865 85737906 hg19_dna 50 + 9 50 4
41
chain 41 chr8 146364022 + 95160479 95160520 hg19_dna 50 + 8 49 5
41
chain 30 chr22 51304566 + 42144400 42144436 hg19_dna 50 + 11 47 6
36
chain 41 chr2 243199373 + 183925984 183926028 hg19_dna 50 + 1 49 7
6       0       4
38
chain 31 chr19 59128983 + 35483340 35483510 hg19_dna 50 + 10 46 8
25      134     0
11
chain 39 chr18 78077248 + 23891310 23891349 hg19_dna 50 + 10 49 9
39
...
\end{minted}
This file was generated by running UCSC's \verb+pslToChain+ program on the PSL file \verb+psl_34_001.psl+. According to the chain file format specification, there should be a blank line after each chain block, but some tools (including \verb+pslToChain+) apparently do not follow this rule.

To parse this file, use
%doctest ../Tests/Blat lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> alignments = Align.parse("psl_34_001.chain", "chain")
\end{minted}
Iterate over alignments to get one \verb|Alignment| object for each chain:
%cont-doctest
\begin{minted}{pycon}
>>> for alignment in alignments:
...     print(alignment.target.id, alignment.query.id)  # doctest: +ELLIPSIS
...
chr4 hg18_dna
chr1 hg18_dna
chr2 hg18_dna
chr9 hg19_dna
chr8 hg19_dna
chr22 hg19_dna
chr2 hg19_dna
...
chr1 hg19_dna
\end{minted}

Rewind the alignments, and iterate from the start until we reach the seventh alignment:
%cont-doctest
\begin{minted}{pycon}
>>> alignments.rewind()
>>> for i in range(7):
...     alignment = next(alignments)
...
\end{minted}
Check the alignment score and chain ID (the first and last number, respectively, in the header line of each chain block) to confirm that we got the seventh alignment:
%cont-doctest
\begin{minted}{pycon}
>>> alignment.score
41.0
>>> alignment.annotations["id"]
'7'
\end{minted}
We can print the alignment in the chain file format. The alignment coordinates are consistent with the information in the chain block, with an aligned section of 6 nucleotides, a gap of 4 nucleotides, and an aligned section of 38 nucleotides:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "chain"))  # doctest: +NORMALIZE_WHITESPACE
chain 41 chr2 243199373 + 183925984 183926028 hg19_dna 50 + 1 49 7
6	0	4
38
<BLANKLINE>
<BLANKLINE>
>>> alignment.coordinates
array([[183925984, 183925990, 183925990, 183926028],
       [        1,         7,        11,        49]])
>>> print(alignment)
chr2      183925984 ??????----?????????????????????????????????????? 183926028
                  0 ||||||----||||||||||||||||||||||||||||||||||||||        48
hg19_dna          1 ????????????????????????????????????????????????        49
<BLANKLINE>
\end{minted}
We can also print the alignment in a few other alignment fite formats:
%cont-doctest
\begin{minted}{pycon}
>>> print(format(alignment, "BED"))  # doctest: +NORMALIZE_WHITESPACE
chr2	183925984	183926028	hg19_dna	41	+	183925984	183926028	0	2	6,38,	0,6,
<BLANKLINE>
>>> print(format(alignment, "PSL"))  # doctest: +NORMALIZE_WHITESPACE
44	0	0	0	1	4	0	0	+	hg19_dna	50	1	49	chr2	243199373	183925984	183926028	2	6,38,	1,11,	183925984,183925990,
<BLANKLINE>
>>> print(format(alignment, "exonerate"))
vulgar: hg19_dna 1 49 + chr2 183925984 183926028 + 41 M 6 6 G 4 0 M 38 38
<BLANKLINE>
>>> print(alignment.format("exonerate", "cigar"))
cigar: hg19_dna 1 49 + chr2 183925984 183926028 + 41 M 6 I 4 M 38
<BLANKLINE>
>>> print(format(alignment, "sam"))  # doctest: +NORMALIZE_WHITESPACE
hg19_dna	0	chr2	183925985	255	1S6M4I38M1S	*	0	0	*	*	AS:i:41	id:A:7
<BLANKLINE>
\end{minted}
