\chapter{Multiple Sequence Alignment objects}
\label{chapter:align}

This chapter is about Multiple Sequence Alignments, by which we mean a collection of
multiple sequences which have been aligned together -- usually with the insertion of gap
characters, and addition of leading or trailing gaps -- such that all the sequence
strings are the same length. Such an alignment can be regarded as a matrix of letters,
where each row is held as a \verb|SeqRecord| object internally.

We will introduce the \verb|MultipleSeqAlignment| object which holds this kind of data,
and the \verb|Bio.AlignIO| module for reading and writing them as various file formats
(following the design of the \verb|Bio.SeqIO| module from the previous chapter).
Note that both \verb|Bio.SeqIO| and \verb|Bio.AlignIO| can read and write sequence
alignment files.  The appropriate choice will depend largely on what you want to do
with the data.

The final part of this chapter is about our command line wrappers for common multiple
sequence alignment tools like ClustalW and MUSCLE.

\section{Parsing or Reading Sequence Alignments}

We have two functions for reading in sequence alignments, \verb|Bio.AlignIO.read()| and \verb|Bio.AlignIO.parse()| which following the convention introduced in \verb|Bio.SeqIO| are for files containing one or multiple alignments respectively.

Using \verb|Bio.AlignIO.parse()| will return an {\textit iterator} which gives \verb|MultipleSeqAlignment| objects.  Iterators are typically used in a for loop.  Examples of situations where you will have multiple different alignments include resampled alignments from the PHYLIP tool \verb|seqboot|, or multiple pairwise alignments from the EMBOSS tools \verb|water| or \verb|needle|, or Bill Pearson's FASTA tools.

However, in many situations you will be dealing with files which contain only a single alignment.  In this case, you should use the \verb|Bio.AlignIO.read()| function which returns a single \verb|MultipleSeqAlignment| object.

Both functions expect two mandatory arguments:

\begin{enumerate}
\item The first argument is a {\textit handle} to read the data from, typically an open file (see Section~\ref{sec:appendix-handles}), or a filename.
\item The second argument is a lower case string specifying the alignment format.  As in \verb|Bio.SeqIO| we don't try and guess the file format for you!  See \url{http://biopython.org/wiki/AlignIO} for a full listing of supported formats.
\end{enumerate}

\noindent There is also an optional \verb|seq_count| argument which is discussed in Section~\ref{sec:AlignIO-count-argument} below for dealing with ambiguous file formats which may contain more than one alignment.

\subsection{Single Alignments}
As an example, consider the following annotation rich protein alignment in the PFAM or Stockholm file format:

\begin{minted}{text}
# STOCKHOLM 1.0
#=GS COATB_BPIKE/30-81  AC P03620.1
#=GS COATB_BPIKE/30-81  DR PDB; 1ifl ; 1-52;
#=GS Q9T0Q8_BPIKE/1-52  AC Q9T0Q8.1
#=GS COATB_BPI22/32-83  AC P15416.1
#=GS COATB_BPM13/24-72  AC P69541.1
#=GS COATB_BPM13/24-72  DR PDB; 2cpb ; 1-49;
#=GS COATB_BPM13/24-72  DR PDB; 2cps ; 1-49;
#=GS COATB_BPZJ2/1-49   AC P03618.1
#=GS Q9T0Q9_BPFD/1-49   AC Q9T0Q9.1
#=GS Q9T0Q9_BPFD/1-49   DR PDB; 1nh4 A; 1-49;
#=GS COATB_BPIF1/22-73  AC P03619.2
#=GS COATB_BPIF1/22-73  DR PDB; 1ifk ; 1-50;
COATB_BPIKE/30-81             AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA
#=GR COATB_BPIKE/30-81  SS    -HHHHHHHHHHHHHH--HHHHHHHH--HHHHHHHHHHHHHHHHHHHHH----
Q9T0Q8_BPIKE/1-52             AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA
COATB_BPI22/32-83             DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA
COATB_BPM13/24-72             AEGDDP...AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA
#=GR COATB_BPM13/24-72  SS    ---S-T...CHCHHHHCCCCTCCCTTCHHHHHHHHHHHHHHHHHHHHCTT--
COATB_BPZJ2/1-49              AEGDDP...AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA
Q9T0Q9_BPFD/1-49              AEGDDP...AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA
#=GR Q9T0Q9_BPFD/1-49   SS    ------...-HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH--
COATB_BPIF1/22-73             FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA
#=GR COATB_BPIF1/22-73  SS    XX-HHHH--HHHHHH--HHHHHHH--HHHHHHHHHHHHHHHHHHHHHHH---
#=GC SS_cons                  XHHHHHHHHHHHHHHHCHHHHHHHHCHHHHHHHHHHHHHHHHHHHHHHHC--
#=GC seq_cons                 AEssss...AptAhDSLpspAT-hIu.sWshVsslVsAsluIKLFKKFsSKA
//
\end{minted}

This is the seed alignment for the Phage\_Coat\_Gp8 (PF05371) PFAM entry, downloaded from a now out of date release of PFAM from \url{https://pfam.xfam.org/}.  We can load this file as follows (assuming it has been saved to disk as ``PF05371\_seed.sth'' in the current working directory):

%doctest examples
\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
\end{minted}

\noindent This code will print out a summary of the alignment:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment)
Alignment with 7 rows and 52 columns
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52
DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRL...SKA COATB_BPI22/32-83
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73
\end{minted}

You'll notice in the above output the sequences have been truncated.  We could instead write our own code to format this as we please by iterating over the rows as \verb|SeqRecord| objects:

%doctest examples
\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
>>> print("Alignment length %i" % alignment.get_alignment_length())
Alignment length 52
>>> for record in alignment:
...     print("%s - %s" % (record.seq, record.id))
...
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA - COATB_BPIKE/30-81
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA - Q9T0Q8_BPIKE/1-52
DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA - COATB_BPI22/32-83
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - COATB_BPM13/24-72
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA - COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - Q9T0Q9_BPFD/1-49
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA - COATB_BPIF1/22-73
\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{sec:alignment-format} for details.

Did you notice in the raw file above that several of the sequences include database cross-references to the PDB and the associated known secondary structure?  Try this:

%cont-doctest
\begin{minted}{pycon}
>>> for record in alignment:
...     if record.dbxrefs:
...         print("%s %s" % (record.id, record.dbxrefs))
...
COATB_BPIKE/30-81 ['PDB; 1ifl ; 1-52;']
COATB_BPM13/24-72 ['PDB; 2cpb ; 1-49;', 'PDB; 2cps ; 1-49;']
Q9T0Q9_BPFD/1-49 ['PDB; 1nh4 A; 1-49;']
COATB_BPIF1/22-73 ['PDB; 1ifk ; 1-50;']
\end{minted}

\noindent To have a look at all the sequence annotation, try this:

\begin{minted}{pycon}
>>> for record in alignment:
...     print(record)
...
\end{minted}

PFAM provide a nice web interface at \url{http://pfam.xfam.org/family/PF05371} which will actually let you download this alignment in several other formats.  This is what the file looks like in the FASTA file format:

\begin{minted}{text}
>COATB_BPIKE/30-81
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA
>Q9T0Q8_BPIKE/1-52
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA
>COATB_BPI22/32-83
DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA
>COATB_BPM13/24-72
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA
>COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA
>Q9T0Q9_BPFD/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA
>COATB_BPIF1/22-73
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA
\end{minted}

\noindent Note the website should have an option about showing gaps as periods (dots) or dashes, we've shown dashes above.  Assuming you download and save this as file ``PF05371\_seed.faa'' then you can load it with almost exactly the same code:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.faa", "fasta")
>>> print(alignment)
\end{minted}

All that has changed in this code is the filename and the format string.  You'll get the same output as before, the sequences and record identifiers are the same.
However, as you should expect, if you check each \verb|SeqRecord| there is no annotation nor database cross-references because these are not included in the FASTA file format.

Note that rather than using the Sanger website, you could have used \verb|Bio.AlignIO| to convert the original Stockholm format file into a FASTA file yourself (see below).

With any supported file format, you can load an alignment in exactly the same way just by changing the format string.  For example, use ``phylip'' for PHYLIP files, ``nexus'' for NEXUS files or ``emboss'' for the alignments output by the EMBOSS tools.  There is a full listing on the wiki page (\url{http://biopython.org/wiki/AlignIO}) and in the built in documentation (also \href{http://biopython.org/docs/\bpversion/api/Bio.AlignIO.html}{online}):

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> help(AlignIO)
\end{minted}

\subsection{Multiple Alignments}

The previous section focused on reading files containing a single alignment.  In general however, files can contain more than one alignment, and to read these files we must use the \verb|Bio.AlignIO.parse()| function.

Suppose you have a small alignment in PHYLIP format:

\begin{minted}{text}
    5    6
Alpha     AACAAC
Beta      AACCCC
Gamma     ACCAAC
Delta     CCACCA
Epsilon   CCAAAC
\end{minted}

If you wanted to bootstrap a phylogenetic tree using the PHYLIP tools, one of the steps would be to create a set of many resampled alignments using the tool \verb|bootseq|.  This would give output something like this, which has been abbreviated for conciseness:

\begin{minted}{text}
    5     6
Alpha     AAACCA
Beta      AAACCC
Gamma     ACCCCA
Delta     CCCAAC
Epsilon   CCCAAA
    5     6
Alpha     AAACAA
Beta      AAACCC
Gamma     ACCCAA
Delta     CCCACC
Epsilon   CCCAAA
    5     6
Alpha     AAAAAC
Beta      AAACCC
Gamma     AACAAC
Delta     CCCCCA
Epsilon   CCCAAC
...
    5     6
Alpha     AAAACC
Beta      ACCCCC
Gamma     AAAACC
Delta     CCCCAA
Epsilon   CAAACC
\end{minted}

If you wanted to read this in using \verb|Bio.AlignIO| you could use:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> alignments = AlignIO.parse("resampled.phy", "phylip")
>>> for alignment in alignments:
...     print(alignment)
...     print()
...
\end{minted}

\noindent This would give the following output, again abbreviated for display:

\begin{minted}{text}
Alignment with 5 rows and 6 columns
AAACCA Alpha
AAACCC Beta
ACCCCA Gamma
CCCAAC Delta
CCCAAA Epsilon

Alignment with 5 rows and 6 columns
AAACAA Alpha
AAACCC Beta
ACCCAA Gamma
CCCACC Delta
CCCAAA Epsilon

Alignment with 5 rows and 6 columns
AAAAAC Alpha
AAACCC Beta
AACAAC Gamma
CCCCCA Delta
CCCAAC Epsilon

...

Alignment with 5 rows and 6 columns
AAAACC Alpha
ACCCCC Beta
AAAACC Gamma
CCCCAA Delta
CAAACC Epsilon
\end{minted}

As with the function \verb|Bio.SeqIO.parse()|, using \verb|Bio.AlignIO.parse()| returns an iterator.
If you want to keep all the alignments in memory at once, which will allow you to access them in any order, then turn the iterator into a list:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> alignments = list(AlignIO.parse("resampled.phy", "phylip"))
>>> last_align = alignments[-1]
>>> first_align = alignments[0]
\end{minted}

\subsection{Ambiguous Alignments}
\label{sec:AlignIO-count-argument}
Many alignment file formats can explicitly store more than one alignment, and the division between each alignment is clear.  However, when a general sequence file format has been used there is no such block structure.  The most common such situation is when alignments have been saved in the FASTA file format.  For example consider the following:

\begin{minted}{text}
>Alpha
ACTACGACTAGCTCAG--G
>Beta
ACTACCGCTAGCTCAGAAG
>Gamma
ACTACGGCTAGCACAGAAG
>Alpha
ACTACGACTAGCTCAGG--
>Beta
ACTACCGCTAGCTCAGAAG
>Gamma
ACTACGGCTAGCACAGAAG
\end{minted}

\noindent This could be a single alignment containing six sequences (with repeated identifiers).  Or, judging from the identifiers, this is probably two different alignments each with three sequences, which happen to all have the same length.

What about this next example?

\begin{minted}{text}
>Alpha
ACTACGACTAGCTCAG--G
>Beta
ACTACCGCTAGCTCAGAAG
>Alpha
ACTACGACTAGCTCAGG--
>Gamma
ACTACGGCTAGCACAGAAG
>Alpha
ACTACGACTAGCTCAGG--
>Delta
ACTACGGCTAGCACAGAAG
\end{minted}

\noindent Again, this could be a single alignment with six sequences.  However this time based on the identifiers we might guess this is three pairwise alignments which by chance have all got the same lengths.

This final example is similar:

\begin{minted}{text}
>Alpha
ACTACGACTAGCTCAG--G
>XXX
ACTACCGCTAGCTCAGAAG
>Alpha
ACTACGACTAGCTCAGG
>YYY
ACTACGGCAAGCACAGG
>Alpha
--ACTACGAC--TAGCTCAGG
>ZZZ
GGACTACGACAATAGCTCAGG
\end{minted}

\noindent In this third example, because of the differing lengths, this cannot be treated as a single alignment containing all six records.  However, it could be three pairwise alignments.

Clearly trying to store more than one alignment in a FASTA file is not ideal.  However, if you are forced to deal with these as input files \verb|Bio.AlignIO| can cope with the most common situation where all the alignments have the same number of records.
One example of this is a collection of pairwise alignments, which can be produced by the EMBOSS tools \verb|needle| and \verb|water| -- although in this situation, \verb|Bio.AlignIO| should be able to understand their native output using ``emboss'' as the format string.

To interpret these FASTA examples as several separate alignments, we can use \verb|Bio.AlignIO.parse()| with the optional \verb|seq_count| argument which specifies how many sequences are expected in each alignment (in these examples, 3, 2 and 2 respectively).
For example, using the third example as the input data:

\begin{minted}{pycon}
>>> for alignment in AlignIO.parse(handle, "fasta", seq_count=2):
...     print("Alignment length %i" % alignment.get_alignment_length())
...     for record in alignment:
...         print("%s - %s" % (record.seq, record.id))
...     print()
...
\end{minted}

\noindent giving:

\begin{minted}{text}
Alignment length 19
ACTACGACTAGCTCAG--G - Alpha
ACTACCGCTAGCTCAGAAG - XXX

Alignment length 17
ACTACGACTAGCTCAGG - Alpha
ACTACGGCAAGCACAGG - YYY

Alignment length 21
--ACTACGAC--TAGCTCAGG - Alpha
GGACTACGACAATAGCTCAGG - ZZZ
\end{minted}

Using \verb|Bio.AlignIO.read()| or \verb|Bio.AlignIO.parse()| without the \verb|seq_count| argument would give a single alignment containing all six records for the first two examples.  For the third example, an exception would be raised because the lengths differ preventing them being turned into a single alignment.

If the file format itself has a block structure allowing \verb|Bio.AlignIO| to determine the number of sequences in each alignment directly, then the \verb|seq_count| argument is not needed.  If it is supplied, and doesn't agree with the file contents, an error is raised.

Note that this optional \verb|seq_count| argument assumes each alignment in the file has the same number of sequences.  Hypothetically you may come across stranger situations, for example a FASTA file containing several alignments each with a different number of sequences -- although I would love to hear of a real world example of this.  Assuming you cannot get the data in a nicer file format, there is no straight forward way to deal with this using \verb|Bio.AlignIO|.  In this case, you could consider reading in the sequences themselves using \verb|Bio.SeqIO| and batching them together to create the alignments as appropriate.

\section{Writing Alignments}

We've talked about using \verb|Bio.AlignIO.read()| and \verb|Bio.AlignIO.parse()| for alignment input (reading files), and now we'll look at \verb|Bio.AlignIO.write()| which is for alignment output (writing files).  This is a function taking three arguments: some \verb|MultipleSeqAlignment| objects (or for backwards compatibility the obsolete \verb|Alignment| objects), a handle or filename to write to, and a sequence format.

Here is an example, where we start by creating a few \verb|MultipleSeqAlignment| objects the hard way (by hand, rather than by loading them from a file).
Note we create some \verb|SeqRecord| objects to construct the alignment from.

%doctest
\begin{minted}{pycon}
>>> from Bio.Seq import Seq
>>> from Bio.SeqRecord import SeqRecord
>>> from Bio.Align import MultipleSeqAlignment
>>> align1 = MultipleSeqAlignment(
...     [
...         SeqRecord(Seq("ACTGCTAGCTAG"), id="Alpha"),
...         SeqRecord(Seq("ACT-CTAGCTAG"), id="Beta"),
...         SeqRecord(Seq("ACTGCTAGDTAG"), id="Gamma"),
...     ]
... )
>>> align2 = MultipleSeqAlignment(
...     [
...         SeqRecord(Seq("GTCAGC-AG"), id="Delta"),
...         SeqRecord(Seq("GACAGCTAG"), id="Epsilon"),
...         SeqRecord(Seq("GTCAGCTAG"), id="Zeta"),
...     ]
... )
>>> align3 = MultipleSeqAlignment(
...     [
...         SeqRecord(Seq("ACTAGTACAGCTG"), id="Eta"),
...         SeqRecord(Seq("ACTAGTACAGCT-"), id="Theta"),
...         SeqRecord(Seq("-CTACTACAGGTG"), id="Iota"),
...     ]
... )
>>> my_alignments = [align1, align2, align3]
\end{minted}

\noindent Now we have a list of \verb|Alignment| objects, we'll write them to a PHYLIP format file:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> AlignIO.write(my_alignments, "my_example.phy", "phylip")
\end{minted}

\noindent And if you open this file in your favourite text editor it should look like this:

\begin{minted}{text}
 3 12
Alpha      ACTGCTAGCT AG
Beta       ACT-CTAGCT AG
Gamma      ACTGCTAGDT AG
 3 9
Delta      GTCAGC-AG
Epislon    GACAGCTAG
Zeta       GTCAGCTAG
 3 13
Eta        ACTAGTACAG CTG
Theta      ACTAGTACAG CT-
Iota       -CTACTACAG GTG
\end{minted}

Its more common to want to load an existing alignment, and save that, perhaps after some simple manipulation like removing certain rows or columns.

Suppose you wanted to know how many alignments the \verb|Bio.AlignIO.write()| function wrote to the handle? If your alignments were in a list like the example above, you could just use \verb|len(my_alignments)|, however you can't do that when your records come from a generator/iterator.  Therefore the \verb|Bio.AlignIO.write()| function returns the number of alignments written to the file.

\emph{Note} - If you tell the \verb|Bio.AlignIO.write()| function to write to a file that already exists, the old file will be overwritten without any warning.


\subsection{Converting between sequence alignment file formats}
\label{sec:converting-alignments}

Converting between sequence alignment file formats with \verb|Bio.AlignIO| works
in the same way as converting between sequence file formats with \verb|Bio.SeqIO|
(Section~\ref{sec:SeqIO-conversion}). We load generally the alignment(s) using
\verb|Bio.AlignIO.parse()| and then save them using the \verb|Bio.AlignIO.write()|
-- or just use the \verb|Bio.AlignIO.convert()| helper function.

For this example, we'll load the PFAM/Stockholm format file used earlier and save it as a Clustal W format file:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> count = AlignIO.convert("PF05371_seed.sth", "stockholm", "PF05371_seed.aln", "clustal")
>>> print("Converted %i alignments" % count)
Converted 1 alignments
\end{minted}

Or, using \verb|Bio.AlignIO.parse()| and \verb|Bio.AlignIO.write()|:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> alignments = AlignIO.parse("PF05371_seed.sth", "stockholm")
>>> count = AlignIO.write(alignments, "PF05371_seed.aln", "clustal")
>>> print("Converted %i alignments" % count)
Converted 1 alignments
\end{minted}

The \verb|Bio.AlignIO.write()| function expects to be given multiple alignment objects.  In the example above we gave it the alignment iterator returned by \verb|Bio.AlignIO.parse()|.

In this case, we know there is only one alignment in the file so we could have used \verb|Bio.AlignIO.read()| instead, but notice we have to pass this alignment to \verb|Bio.AlignIO.write()| as a single element list:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
>>> AlignIO.write([alignment], "PF05371_seed.aln", "clustal")
\end{minted}

Either way, you should end up with the same new Clustal W format file ``PF05371\_seed.aln'' with the following content:

\begin{minted}{text}
CLUSTAL X (1.81) multiple sequence alignment


COATB_BPIKE/30-81                   AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSS
Q9T0Q8_BPIKE/1-52                   AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVS
COATB_BPI22/32-83                   DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSS
COATB_BPM13/24-72                   AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTS
COATB_BPZJ2/1-49                    AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFAS
Q9T0Q9_BPFD/1-49                    AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTS
COATB_BPIF1/22-73                   FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVS

COATB_BPIKE/30-81                   KA
Q9T0Q8_BPIKE/1-52                   RA
COATB_BPI22/32-83                   KA
COATB_BPM13/24-72                   KA
COATB_BPZJ2/1-49                    KA
Q9T0Q9_BPFD/1-49                    KA
COATB_BPIF1/22-73                   RA
\end{minted}

Alternatively, you could make a PHYLIP format file which we'll name ``PF05371\_seed.phy'':

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> AlignIO.convert("PF05371_seed.sth", "stockholm", "PF05371_seed.phy", "phylip")
\end{minted}

This time the output looks like this:

\begin{minted}{text}
 7 52
COATB_BPIK AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIRLFKKFSS
Q9T0Q8_BPI AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIKLFKKFVS
COATB_BPI2 DGTSTATSYA TEAMNSLKTQ ATDLIDQTWP VVTSVAVAGL AIRLFKKFSS
COATB_BPM1 AEGDDP---A KAAFNSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS
COATB_BPZJ AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFAS
Q9T0Q9_BPF AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS
COATB_BPIF FAADDATSQA KAAFDSLTAQ ATEMSGYAWA LVVLVVGATV GIKLFKKFVS

           KA
           RA
           KA
           KA
           KA
           KA
           RA
\end{minted}

One of the big handicaps of the original PHYLIP alignment file format is
that the sequence identifiers are strictly truncated at ten characters.
In this example, as you can see the resulting names are still unique -
but they are not very readable. As a result, a more relaxed variant of
the original PHYLIP format is now quite widely used:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> AlignIO.convert("PF05371_seed.sth", "stockholm", "PF05371_seed.phy", "phylip-relaxed")
\end{minted}

This time the output looks like this, using a longer indentation to
allow all the identifiers to be given in full:

\begin{minted}{text}
 7 52
COATB_BPIKE/30-81  AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIRLFKKFSS
Q9T0Q8_BPIKE/1-52  AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIKLFKKFVS
COATB_BPI22/32-83  DGTSTATSYA TEAMNSLKTQ ATDLIDQTWP VVTSVAVAGL AIRLFKKFSS
COATB_BPM13/24-72  AEGDDP---A KAAFNSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS
COATB_BPZJ2/1-49   AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFAS
Q9T0Q9_BPFD/1-49   AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS
COATB_BPIF1/22-73  FAADDATSQA KAAFDSLTAQ ATEMSGYAWA LVVLVVGATV GIKLFKKFVS

                   KA
                   RA
                   KA
                   KA
                   KA
                   KA
                   RA
\end{minted}

If you have to work with the original strict PHYLIP format, then you may need to
compress the identifiers somehow -- or assign your own names or numbering system.
This following bit of code manipulates the record identifiers before saving the output:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
>>> name_mapping = {}
>>> for i, record in enumerate(alignment):
...     name_mapping[i] = record.id
...     record.id = "seq%i" % i
...
>>> print(name_mapping)
{0: 'COATB_BPIKE/30-81', 1: 'Q9T0Q8_BPIKE/1-52', 2: 'COATB_BPI22/32-83', 3: 'COATB_BPM13/24-72', 4: 'COATB_BPZJ2/1-49', 5: 'Q9T0Q9_BPFD/1-49', 6: 'COATB_BPIF1/22-73'}
>>> AlignIO.write([alignment], "PF05371_seed.phy", "phylip")
\end{minted}

\noindent This code used a Python dictionary to record a simple mapping from the new sequence system to the original identifier:
\begin{minted}{python}
{
    0: "COATB_BPIKE/30-81",
    1: "Q9T0Q8_BPIKE/1-52",
    2: "COATB_BPI22/32-83",
    # ...
}
\end{minted}

\noindent Here is the new (strict) PHYLIP format output:
\begin{minted}{text}
 7 52
seq0       AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIRLFKKFSS
seq1       AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIKLFKKFVS
seq2       DGTSTATSYA TEAMNSLKTQ ATDLIDQTWP VVTSVAVAGL AIRLFKKFSS
seq3       AEGDDP---A KAAFNSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS
seq4       AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFAS
seq5       AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS
seq6       FAADDATSQA KAAFDSLTAQ ATEMSGYAWA LVVLVVGATV GIKLFKKFVS

           KA
           RA
           KA
           KA
           KA
           KA
           RA
\end{minted}

\noindent In general, because of the identifier limitation, working with
\textit{strict} PHYLIP file formats shouldn't be your first choice.
Using the PFAM/Stockholm format on the other hand allows you to record a lot of additional annotation too.

\subsection{Getting your alignment objects as formatted strings}
\label{sec:alignment-format}
The \verb|Bio.AlignIO| interface is based on handles, which means if you want to get your alignment(s) into a string in a particular file format you need to do a little bit more work (see below).
However, you will probably prefer to call Python's built-in \verb|format| function on the alignment object.
This takes an output format specification as a single argument, a lower case string which is supported by \verb|Bio.AlignIO| as an output format.  For example:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
>>> print(format(alignment, "clustal"))
CLUSTAL X (1.81) multiple sequence alignment


COATB_BPIKE/30-81                   AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSS
Q9T0Q8_BPIKE/1-52                   AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVS
COATB_BPI22/32-83                   DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSS
...
\end{minted}

Without an output format specification, \verb|format| returns the same output as \verb|str|.

As described in Section~\ref{sec:SeqRecord-format}, the \verb|SeqRecord| object has a similar method using output formats supported by \verb|Bio.SeqIO|.

Internally \verb|format| is calling \verb|Bio.AlignIO.write()| with a \verb|StringIO| handle.  You can do this in your own code if for example you are using an
older version of Biopython:

\begin{minted}{pycon}
>>> from io import StringIO
>>> from Bio import AlignIO
>>> alignments = AlignIO.parse("PF05371_seed.sth", "stockholm")
>>> out_handle = StringIO()
>>> AlignIO.write(alignments, out_handle, "clustal")
1
>>> clustal_data = out_handle.getvalue()
>>> print(clustal_data)
CLUSTAL X (1.81) multiple sequence alignment


COATB_BPIKE/30-81                   AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSS
Q9T0Q8_BPIKE/1-52                   AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVS
COATB_BPI22/32-83                   DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSS
COATB_BPM13/24-72                   AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTS
...
\end{minted}

\section{Manipulating Alignments}
\label{sec:manipulating-alignments}

Now that we've covered loading and saving alignments, we'll look at what else you can do
with them.

\subsection{Slicing alignments}
First of all, in some senses the alignment objects act like a Python \verb|list| of
\verb|SeqRecord| objects (the rows). With this model in mind hopefully the actions
of \verb|len()| (the number of rows) and iteration (each row as a \verb|SeqRecord|)
make sense:

%doctest examples
\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
>>> print("Number of rows: %i" % len(alignment))
Number of rows: 7
>>> for record in alignment:
...     print("%s - %s" % (record.seq, record.id))
...
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA - COATB_BPIKE/30-81
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA - Q9T0Q8_BPIKE/1-52
DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA - COATB_BPI22/32-83
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - COATB_BPM13/24-72
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA - COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - Q9T0Q9_BPFD/1-49
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA - COATB_BPIF1/22-73
\end{minted}

You can also use the list-like \verb|append| and \verb|extend| methods to add
more rows to the alignment (as \verb|SeqRecord| objects). Keeping the list
metaphor in mind, simple slicing of the alignment should also make sense -
it selects some of the rows giving back another alignment object:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment)
Alignment with 7 rows and 52 columns
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52
DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRL...SKA COATB_BPI22/32-83
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73
>>> print(alignment[3:7])
Alignment with 4 rows and 52 columns
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73
\end{minted}

What if you wanted to select by column? Those of you who have used the NumPy
matrix or array objects won't be surprised at this - you use a double index.

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment[2, 6])
T
\end{minted}

\noindent Using two integer indices pulls out a single letter, short hand for this:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment[2].seq[6])
T
\end{minted}

You can pull out a single column as a string like this:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment[:, 6])
TTT---T
\end{minted}

You can also select a range of columns. For example, to pick out those same
three rows we extracted earlier, but take just their first six columns:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment[3:6, :6])
Alignment with 3 rows and 6 columns
AEGDDP COATB_BPM13/24-72
AEGDDP COATB_BPZJ2/1-49
AEGDDP Q9T0Q9_BPFD/1-49
\end{minted}

Leaving the first index as \verb|:| means take all the rows:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment[:, :6])
Alignment with 7 rows and 6 columns
AEPNAA COATB_BPIKE/30-81
AEPNAA Q9T0Q8_BPIKE/1-52
DGTSTA COATB_BPI22/32-83
AEGDDP COATB_BPM13/24-72
AEGDDP COATB_BPZJ2/1-49
AEGDDP Q9T0Q9_BPFD/1-49
FAADDA COATB_BPIF1/22-73
\end{minted}

This brings us to a neat way to remove a section. Notice columns
7, 8 and 9 which are gaps in three of the seven sequences:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment[:, 6:9])
Alignment with 7 rows and 3 columns
TNY COATB_BPIKE/30-81
TNY Q9T0Q8_BPIKE/1-52
TSY COATB_BPI22/32-83
--- COATB_BPM13/24-72
--- COATB_BPZJ2/1-49
--- Q9T0Q9_BPFD/1-49
TSQ COATB_BPIF1/22-73
\end{minted}

\noindent Again, you can slice to get everything after the ninth column:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment[:, 9:])
Alignment with 7 rows and 43 columns
ATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81
ATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52
ATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83
AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA COATB_BPM13/24-72
AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49
AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49
AKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73
\end{minted}

\noindent Now, the interesting thing is that addition of alignment objects works
by column. This lets you do this as a way to remove a block of columns:

%cont-doctest
\begin{minted}{pycon}
>>> edited = alignment[:, :6] + alignment[:, 9:]
>>> print(edited)
Alignment with 7 rows and 49 columns
AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81
AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52
DGTSTAATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83
AEGDDPAKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA COATB_BPM13/24-72
AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49
AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49
FAADDAAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73
\end{minted}

Another common use of alignment addition would be to combine alignments for
several different genes into a meta-alignment. Watch out though - the identifiers
need to match up (see Section~\ref{sec:SeqRecord-addition} for how adding
\verb|SeqRecord| objects works). You may find it helpful to first sort the
alignment rows alphabetically by id:

%cont-doctest
\begin{minted}{pycon}
>>> edited.sort()
>>> print(edited)
Alignment with 7 rows and 49 columns
DGTSTAATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83
FAADDAAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73
AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81
AEGDDPAKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA COATB_BPM13/24-72
AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49
AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52
AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49
\end{minted}

\noindent Note that you can only add two alignments together if they
have the same number of rows.

\subsection{Alignments as arrays}
Depending on what you are doing, it can be more useful to turn the alignment
object into an array of letters -- and you can do this with NumPy:

%doctest examples lib:numpy
\begin{minted}{pycon}
>>> import numpy as np
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
>>> align_array = np.array([list(rec) for rec in alignment], np.character)
>>> print("Array shape %i by %i" % align_array.shape)
Array shape 7 by 52
\end{minted}

If you will be working heavily with the columns, you can tell NumPy to store
the array by column (as in Fortran) rather than its default of by row (as in C):

\begin{minted}{pycon}
>>> align_array = np.array([list(rec) for rec in alignment], np.character, order="F")
\end{minted}

Note that this leaves the original Biopython alignment object and the NumPy array
in memory as separate objects - editing one will not update the other!

\section{Getting information on the alignment}

\subsection{Substitutions}

The \verb+substitutions+ property of an alignment reports how often letters in the alignment are substituted for each other. This is calculated by taking all pairs of rows in the alignment, counting the number of times two letters are aligned to each other, and summing this over all pairs. For example,

%doctest
\begin{minted}{pycon}
>>> from Bio.Seq import Seq
>>> from Bio.SeqRecord import SeqRecord
>>> from Bio.Align import MultipleSeqAlignment
>>> alignment = MultipleSeqAlignment(
...     [
...         SeqRecord(Seq("ACTCCTA"), id='seq1'),
...         SeqRecord(Seq("AAT-CTA"), id='seq2'),
...         SeqRecord(Seq("CCTACT-"), id='seq3'),
...         SeqRecord(Seq("TCTCCTC"), id='seq4'),
...     ]
... )
...
>>> print(alignment)
Alignment with 4 rows and 7 columns
ACTCCTA seq1
AAT-CTA seq2
CCTACT- seq3
TCTCCTC seq4
>>> substitutions = alignment.substitutions
>>> print(substitutions)
    A    C    T
A 2.0  4.5  1.0
C 4.5 10.0  0.5
T 1.0  0.5 12.0
<BLANKLINE>
\end{minted}
As the ordering of pairs is arbitrary, counts are divided equally above and below the diagonal. For example, the 9 alignments of \verb+A+ to \verb+C+ are stored as 4.5 at position \verb+['A', 'C']+ and 4.5  at position \verb+['C', 'A']+. This arrangement helps to make the math easier when calculating a substitution matrix from these counts, as described in Section~\ref{sec:subs_mat_ex}.

Note that \verb+alignment.substitutions+ contains entries for the letters appearing in the alignment only. You can use the \verb+select+ method to add entries for missing letters, for example
%cont-doctest
\begin{minted}{pycon}
>>> m = substitutions.select("ATCG")
>>> print(m)
    A    T    C   G
A 2.0  1.0  4.5 0.0
T 1.0 12.0  0.5 0.0
C 4.5  0.5 10.0 0.0
G 0.0  0.0  0.0 0.0
<BLANKLINE>
\end{minted}
This also allows you to change the order of letters in the alphabet.

\section{Alignment Tools}
\label{sec:alignment-tools}

There are \emph{lots} of algorithms out there for aligning sequences, both pairwise alignments
and multiple sequence alignments. These calculations are relatively slow, and you generally
wouldn't want to write such an algorithm in Python. For pairwise alignments Biopython contains
the \verb|Bio.pairwise2| module , which is supplemented by functions written in C for speed
enhancements and the new \verb|PairwiseAligner| (see Section~\ref{sec:pairwise}). In addition,
you can use Biopython to invoke a command line tool on your behalf. Normally you would:
\begin{enumerate}
\item Prepare an input file of your unaligned sequences, typically this will be a FASTA file
      which you might create using \verb|Bio.SeqIO| (see Chapter~\ref{chapter:seqio}).
\item Call the command line tool to process this input file, typically via one of Biopython's
      command line wrappers (which we'll discuss here).
\item Read the output from the tool, i.e. your aligned sequences, typically using
      \verb|Bio.AlignIO| (see earlier in this chapter).
\end{enumerate}

All the command line wrappers we're going to talk about in this chapter follow the same style.
You create a command line object specifying the options (e.g. the input filename and the
output filename), then invoke this command line via a Python operating system call (e.g.
using the \texttt{subprocess} module).

Most of these wrappers are defined in the \verb|Bio.Align.Applications| module:

%doctest
\begin{minted}{pycon}
>>> import Bio.Align.Applications
>>> dir(Bio.Align.Applications) # doctest:+ELLIPSIS
['ClustalOmegaCommandline', 'ClustalwCommandline', 'DialignCommandline', 'MSAProbsCommandline', 'MafftCommandline', 'MuscleCommandline', 'PrankCommandline', 'ProbconsCommandline', 'TCoffeeCommandline', ...]
\end{minted}

\noindent (Ignore the entries starting with an underscore -- these have
special meaning in Python.)
The module \verb|Bio.Emboss.Applications| has wrappers for some of the
\href{http://emboss.sourceforge.net/}{EMBOSS suite}, including
\texttt{needle} and \texttt{water}, which are described below in
Section~\ref{sec:emboss-needle-water}, and wrappers for the EMBOSS
packaged versions of the PHYLIP tools (which EMBOSS refer to as one
of their EMBASSY packages - third party tools with an EMBOSS style
interface).
We won't explore all these alignment tools here in the section, just a
sample, but the same principles apply.

\subsection{ClustalW}
\label{sec:align_clustal}
ClustalW is a popular command line tool for multiple sequence alignment
(there is also a graphical interface called ClustalX). Biopython's
\verb|Bio.Align.Applications| module has a wrapper for this alignment tool
(and several others).

Before trying to use ClustalW from within Python, you should first try running
the ClustalW tool yourself by hand at the command line, to familiarise
yourself the other options. You'll find the Biopython wrapper is very
faithful to the actual command line API:

\begin{minted}{pycon}
>>> from Bio.Align.Applications import ClustalwCommandline
>>> help(ClustalwCommandline)
\end{minted}

For the most basic usage, all you need is to have a FASTA input file, such as
\href{https://raw.githubusercontent.com/biopython/biopython/master/Doc/examples/opuntia.fasta}{opuntia.fasta}
(available online or in the Doc/examples subdirectory of the Biopython source
code). This is a small FASTA file containing seven prickly-pear DNA sequences
(from the cactus family \textit{Opuntia}).

By default ClustalW will generate an alignment and guide tree file with names
based on the input FASTA file, in this case \texttt{opuntia.aln} and
\texttt{opuntia.dnd}, but you can override this or make it explicit:

%doctest
\begin{minted}{pycon}
>>> from Bio.Align.Applications import ClustalwCommandline
>>> cline = ClustalwCommandline("clustalw2", infile="opuntia.fasta")
>>> print(cline)
clustalw2 -infile=opuntia.fasta
\end{minted}

Notice here we have given the executable name as \texttt{clustalw2},
indicating we have version two installed, which has a different filename to
version one (\texttt{clustalw}, the default). Fortunately both versions
support the same set of arguments at the command line (and indeed, should be
functionally identical).

You may find that even though you have ClustalW installed, the above command
doesn't work -- you may get a message about ``command not found'' (especially
on Windows). This indicated that the ClustalW executable is not on your PATH
(an environment variable, a list of directories to be searched). You can
either update your PATH setting to include the location of your copy of
ClustalW tools (how you do this will depend on your OS), or simply type in
the full path of the tool. For example:

%doctest
\begin{minted}{pycon}
>>> import os
>>> from Bio.Align.Applications import ClustalwCommandline
>>> clustalw_exe = r"C:\Program Files\new clustal\clustalw2.exe"
>>> clustalw_cline = ClustalwCommandline(clustalw_exe, infile="opuntia.fasta")
\end{minted}
%Don't run it in the doctest
\begin{minted}{pycon}
>>> assert os.path.isfile(clustalw_exe), "Clustal W executable missing"
>>> stdout, stderr = clustalw_cline()
\end{minted}

\noindent Remember, in Python strings \verb|\n| and \verb|\t| are by default
interpreted as a new line and a tab -- which is why we're put a letter
``r'' at the start for a raw string that isn't translated in this way.
This is generally good practice when specifying a Windows style file name.

Internally this uses the
\verb|subprocess| module which is now the recommended way to run another
program in Python. This replaces older options like the \verb|os.system()|
and the \verb|os.popen*| functions.

Now, at this point it helps to know about how command line tools ``work''.
When you run a tool at the command line, it will often print text output
directly to screen. This text can be captured or redirected, via
two ``pipes'', called standard output (the normal results) and standard
error (for error messages and debug messages). There is also standard
input, which is any text fed into the tool. These names get shortened
to stdin, stdout and stderr. When the tool finishes, it has a return
code (an integer), which by convention is zero for success.

When you run the command line tool like this via the Biopython wrapper,
it will wait for it to finish, and check the return code. If this is
non zero (indicating an error), an exception is raised. The wrapper
then returns two strings, stdout and stderr.

In the case of ClustalW, when run at the command line all the important
output is written directly to the output files. Everything normally printed to
screen while you wait (via stdout or stderr) is boring and can be
ignored (assuming it worked).

What we care about are the two output files, the alignment and the guide
tree. We didn't tell ClustalW what filenames to use, but it defaults to
picking names based on the input file. In this case the output should be
in the file \verb|opuntia.aln|.
You should be able to work out how to read in the alignment using
\verb|Bio.AlignIO| by now:

%doctest examples
\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> align = AlignIO.read("opuntia.aln", "clustal")
>>> print(align)
Alignment with 7 rows and 906 columns
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191
\end{minted}

In case you are interested (and this is an aside from the main thrust of this
chapter), the \texttt{opuntia.dnd} file ClustalW creates is just a standard
Newick tree file, and \verb|Bio.Phylo| can parse these:


%doctest examples
\begin{minted}{pycon}
>>> from Bio import Phylo
>>> tree = Phylo.read("opuntia.dnd", "newick")
>>> Phylo.draw_ascii(tree)
                             _______________ gi|6273291|gb|AF191665.1|AF191665
  __________________________|
 |                          |   ______ gi|6273290|gb|AF191664.1|AF191664
 |                          |__|
 |                             |_____ gi|6273289|gb|AF191663.1|AF191663
 |
_|_________________ gi|6273287|gb|AF191661.1|AF191661
 |
 |__________ gi|6273286|gb|AF191660.1|AF191660
 |
 |    __ gi|6273285|gb|AF191659.1|AF191659
 |___|
     | gi|6273284|gb|AF191658.1|AF191658
<BLANKLINE>
\end{minted}

\noindent Chapter \ref{chapter:phylo} covers Biopython's support for phylogenetic trees in more
depth.

\subsection{MUSCLE}
MUSCLE is a more recent multiple sequence alignment tool than ClustalW, and
Biopython also has a wrapper for it under the \verb|Bio.Align.Applications|
module. As before, we recommend you try using MUSCLE from the command line before
trying it from within Python, as the Biopython wrapper is very faithful to the
actual command line API:

\begin{minted}{pycon}
>>> from Bio.Align.Applications import MuscleCommandline
>>> help(MuscleCommandline)
\end{minted}

For the most basic usage, all you need is to have a FASTA input file, such as
\href{https://raw.githubusercontent.com/biopython/biopython/master/Doc/examples/opuntia.fasta}{opuntia.fasta}
(available online or in the Doc/examples subdirectory of the Biopython source
code). You can then tell MUSCLE to read in this FASTA file, and write the
alignment to an output file:

%doctest
\begin{minted}{pycon}
>>> from Bio.Align.Applications import MuscleCommandline
>>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.txt")
>>> print(cline)
muscle -in opuntia.fasta -out opuntia.txt
\end{minted}

Note that MUSCLE uses ``-in'' and ``-out'' but in Biopython we have to use
``input'' and ``out'' as the keyword arguments or property names. This is
because ``in'' is a reserved word in Python.

By default MUSCLE will output the alignment as a FASTA file (using gapped
sequences). The \verb|Bio.AlignIO| module should be able to read this
alignment using \texttt{format="fasta"}.
You can also ask for ClustalW-like output:

%doctest
\begin{minted}{pycon}
>>> from Bio.Align.Applications import MuscleCommandline
>>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.aln", clw=True)
>>> print(cline)
muscle -in opuntia.fasta -out opuntia.aln -clw
\end{minted}

Or, strict ClustalW output where the original ClustalW header line is
used for maximum compatibility:

%doctest
\begin{minted}{pycon}
>>> from Bio.Align.Applications import MuscleCommandline
>>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.aln", clwstrict=True)
>>> print(cline)
muscle -in opuntia.fasta -out opuntia.aln -clwstrict
\end{minted}

\noindent The \verb|Bio.AlignIO| module should be able to read these alignments
using \texttt{format="clustal"}.

MUSCLE can also output in GCG MSF format (using the \texttt{msf} argument), but
Biopython can't currently parse that, or using HTML which would give a human
readable web page (not suitable for parsing).

You can also set the other optional parameters, for example the maximum number
of iterations. See the built in help for details.

You would then run MUSCLE command line string as described above for
ClustalW, and parse the output using \verb|Bio.AlignIO| to get an
alignment object.

\subsection{MUSCLE using stdout}

Using a MUSCLE command line as in the examples above will write the alignment
to a file. This means there will be no important information written to the
standard out (stdout) or standard error (stderr) handles. However, by default
MUSCLE will write the alignment to standard output (stdout). We can take
advantage of this to avoid having a temporary output file! For example:

%doctest
\begin{minted}{pycon}
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
>>> print(muscle_cline)
muscle -in opuntia.fasta
\end{minted}

If we run this via the wrapper, we get back the output as a string. In order
to parse this we can use \verb|StringIO| to turn it into a handle.
Remember that MUSCLE defaults to using FASTA as the output format:

\begin{minted}{pycon}
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
>>> stdout, stderr = muscle_cline()
>>> from io import StringIO
>>> from Bio import AlignIO
>>> align = AlignIO.read(StringIO(stdout), "fasta")
>>> print(align)
Alignment with 7 rows and 906 columns
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191663
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191665
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191664
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191661
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191660
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191659
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191658
\end{minted}

The above approach is fairly simple, but if you are dealing with very large output
text the fact that all of stdout and stderr is loaded into memory as a string can
be a potential drawback. Using the \verb|subprocess| module we can work directly
with handles instead:

\begin{minted}{pycon}
>>> import subprocess
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
>>> child = subprocess.Popen(str(muscle_cline),
...                          stdout=subprocess.PIPE,
...                          stderr=subprocess.PIPE,
...                          universal_newlines=True,
...                          shell=(sys.platform!="win32"))
...
>>> from Bio import AlignIO
>>> align = AlignIO.read(child.stdout, "fasta")
>>> print(align)
Alignment with 7 rows and 906 columns
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191663
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191665
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191664
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191661
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191660
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191659
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191658
\end{minted}

\subsection{MUSCLE using stdin and stdout}

We don't actually \emph{need} to have our FASTA input sequences prepared in a file,
because by default MUSCLE will read in the input sequence from standard input!
Note this is a bit more advanced and fiddly, so don't bother with this technique
unless you need to.

First, we'll need some unaligned sequences in memory as \verb|SeqRecord| objects.
For this demonstration I'm going to use a filtered version of the original FASTA
file (using a generator expression), taking just six of the seven sequences:

%doctest
\begin{minted}{pycon}
>>> from Bio import SeqIO
>>> records = (r for r in SeqIO.parse("opuntia.fasta", "fasta") if len(r) < 900)
\end{minted}

Then we create the MUSCLE command line, leaving the input and output to their
defaults (stdin and stdout). I'm also going to ask for strict ClustalW format
as for the output.

%doctest
\begin{minted}{pycon}
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(clwstrict=True)
>>> print(muscle_cline)
muscle -clwstrict
\end{minted}

Now for the fiddly bits using the \verb|subprocess| module, stdin and stdout:

\begin{minted}{pycon}
>>> import subprocess
>>> import sys
>>> child = subprocess.Popen(str(cline),
...                          stdin=subprocess.PIPE,
...                          stdout=subprocess.PIPE,
...                          stderr=subprocess.PIPE,
...                          universal_newlines=True,
...                          shell=(sys.platform!="win32"))
\end{minted}

That should start MUSCLE, but it will be sitting waiting for its FASTA input
sequences, which we must supply via its stdin handle:

\begin{minted}{pycon}
>>> SeqIO.write(records, child.stdin, "fasta")
6
>>> child.stdin.close()
\end{minted}

After writing the six sequences to the handle, MUSCLE will still be waiting
to see if that is all the FASTA sequences or not -- so we must signal that
this is all the input data by closing the handle. At that point MUSCLE should
start to run, and we can ask for the output:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> align = AlignIO.read(child.stdout, "clustal")
>>> print(align)
Alignment with 6 rows and 900 columns
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF19166
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF19166
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF19166
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF19166
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF19165
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF19165
\end{minted}

Wow! There we are with a new alignment of just the six records, without having created
a temporary FASTA input file, or a temporary alignment output file. However, a word of
caution: Dealing with errors with this style of calling external programs is much more
complicated.
It also becomes far harder to diagnose problems, because you can't try running MUSCLE
manually outside of Biopython (because you don't have the input file to supply).
There can also be subtle cross platform issues (e.g. Windows versus Linux), and how
you run your script can have an impact (e.g. at the command line, from IDLE or an
IDE, or as a GUI script). These are all generic Python issues though, and not
specific to Biopython.

If you find working directly with \texttt{subprocess} like this scary, there is an
alternative. If you execute the tool with \texttt{muscle\_cline()} you can supply
any standard input as a big string, \texttt{muscle\_cline(stdin=...)}. So,
provided your data isn't very big, you can prepare the FASTA input in memory as
a string using \texttt{StringIO} (see Section~\ref{sec:appendix-handles}):

%doctest
\begin{minted}{pycon}
>>> from Bio import SeqIO
>>> records = (r for r in SeqIO.parse("opuntia.fasta", "fasta") if len(r) < 900)
>>> from io import StringIO
>>> handle = StringIO()
>>> SeqIO.write(records, handle, "fasta")
6
>>> data = handle.getvalue()
\end{minted}

\noindent You can then run the tool and parse the alignment as follows:

%not a doctest as can't assume the MUSCLE binary is present
\begin{minted}{pycon}
>>> stdout, stderr = muscle_cline(stdin=data)
>>> from Bio import AlignIO
>>> align = AlignIO.read(StringIO(stdout), "clustal")
>>> print(align)
Alignment with 6 rows and 900 columns
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF19166
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF19166
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF19166
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF19166
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF19165
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF19165
\end{minted}

You might find this easier, but it does require more memory (RAM) for the strings
used for the input FASTA and output Clustal formatted data.

\subsection{EMBOSS needle and water}
\label{sec:emboss-needle-water}
The \href{http://emboss.sourceforge.net/}{EMBOSS} suite includes the \texttt{water} and
\texttt{needle} tools for Smith-Waterman algorithm local alignment, and Needleman-Wunsch
global alignment. The tools share the same style interface, so switching between the two
is trivial -- we'll just use \texttt{needle} here.

Suppose you want to do a global pairwise alignment between two sequences, prepared in
FASTA format as follows:

\begin{minted}{text}
>HBA_HUMAN
MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHG
KKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTP
AVHASLDKFLASVSTVLTSKYR
\end{minted}

\noindent in a file \texttt{alpha.faa}, and secondly in a file \texttt{beta.faa}:

\begin{minted}{text}
>HBB_HUMAN
MVHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQRFFESFGDLSTPDAVMGNPK
VKAHGKKVLGAFSDGLAHLDNLKGTFATLSELHCDKLHVDPENFRLLGNVLVCVLAHHFG
KEFTPPVQAAYQKVVAGVANALAHKYH
\end{minted}

You can find copies of these example files with the Biopython source code
under the \verb|Doc/examples/| directory.

Let's start by creating a complete \texttt{needle} command line object in one go:

%doctest
\begin{minted}{pycon}
>>> from Bio.Emboss.Applications import NeedleCommandline
>>> needle_cline = NeedleCommandline(asequence="alpha.faa", bsequence="beta.faa",
...                                  gapopen=10, gapextend=0.5, outfile="needle.txt")
>>> print(needle_cline)
needle -outfile=needle.txt -asequence=alpha.faa -bsequence=beta.faa -gapopen=10 -gapextend=0.5
\end{minted}

Why not try running this by hand at the command prompt? You should see it does a
pairwise comparison and records the output in the file \texttt{needle.txt} (in the
default EMBOSS alignment file format).

Even if you have EMBOSS installed, running this command may not work -- you
might get a message about ``command not found'' (especially on Windows). This
probably means that the EMBOSS tools are not on your PATH environment
variable. You can either update your PATH setting, or simply tell Biopython
the full path to the tool, for example:

%doctest
\begin{minted}{pycon}
>>> from Bio.Emboss.Applications import NeedleCommandline
>>> needle_cline = NeedleCommandline(r"C:\EMBOSS\needle.exe",
...                                  asequence="alpha.faa", bsequence="beta.faa",
...                                  gapopen=10, gapextend=0.5, outfile="needle.txt")
\end{minted}

\noindent Remember in Python that for a default string \verb|\n| or \verb|\t| means a
new line or a tab -- which is why we're put a letter ``r'' at the start for a raw string.

At this point it might help to try running the EMBOSS tools yourself by hand at the
command line, to familiarise yourself the other options and compare them to the
Biopython help text:

\begin{minted}{pycon}
>>> from Bio.Emboss.Applications import NeedleCommandline
>>> help(NeedleCommandline)
\end{minted}

Note that you can also specify (or change or look at) the settings like this:

%doctest
\begin{minted}{pycon}
>>> from Bio.Emboss.Applications import NeedleCommandline
>>> needle_cline = NeedleCommandline()
>>> needle_cline.asequence="alpha.faa"
>>> needle_cline.bsequence="beta.faa"
>>> needle_cline.gapopen=10
>>> needle_cline.gapextend=0.5
>>> needle_cline.outfile="needle.txt"
>>> print(needle_cline)
needle -outfile=needle.txt -asequence=alpha.faa -bsequence=beta.faa -gapopen=10 -gapextend=0.5
>>> print(needle_cline.outfile)
needle.txt
\end{minted}

Next we want to use Python to run this command for us. As explained above,
for full control, we recommend you use the built in Python \texttt{subprocess}
module, but for simple usage the wrapper object usually suffices:

\begin{minted}{pycon}
>>> stdout, stderr = needle_cline()
>>> print(stdout + stderr)
Needleman-Wunsch global alignment of two sequences
\end{minted}

Next we can load the output file with \verb|Bio.AlignIO| as
discussed earlier in this chapter, as the \texttt{emboss} format:

\begin{minted}{pycon}
>>> from Bio import AlignIO
>>> align = AlignIO.read("needle.txt", "emboss")
>>> print(align)
Alignment with 2 rows and 149 columns
MV-LSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTY...KYR HBA_HUMAN
MVHLTPEEKSAVTALWGKV--NVDEVGGEALGRLLVVYPWTQRF...KYH HBB_HUMAN
\end{minted}

In this example, we told EMBOSS to write the output to a file, but you
\emph{can} tell it to write the output to stdout instead (useful if you
don't want a temporary output file to get rid of -- use
\texttt{stdout=True} rather than the \texttt{outfile} argument), and
also to read \emph{one} of the one of the inputs from stdin (e.g.
\texttt{asequence="stdin"}, much like in the MUSCLE example in the
section above).

This has only scratched the surface of what you can do with \texttt{needle}
and \texttt{water}. One useful trick is that the second file can contain
multiple sequences (say five), and then EMBOSS will do five pairwise
alignments.


\section{Pairwise sequence alignment}
\label{sec:pairwise}

Pairwise sequence alignment is the process of aligning two sequences to each
other by optimizing the similarity score between them. Biopython includes two
built-in pairwise aligners: the 'old' \verb|Bio.pairwise2| module and the new
\verb|PairwiseAligner| class within the \verb|Bio.Align| module (since Biopython
version 1.72). Both can perform global and local alignments and offer numerous
options to change the alignment parameters. Although \verb|pairwise2| has gained
some speed and memory enhancements recently, the new \verb|PairwiseAligner| is
much faster; so if you need to make many alignments with larger sequences, the
latter would be the tool to choose. \verb|pairwise2|, on the contrary, is also
able to align lists, which can be useful if your sequences do not consist of
single characters only. 

Given that the parameters and sequences are the same, both aligners will return
the same alignments and alignment score (if the number of alignments is too high
they may return different subsets of all valid alignments).

\subsection{pairwise2}
\label{sec:pairwise2}

\verb|Bio.pairwise2| contains essentially the same algorithms as
\texttt{water} (local) and \texttt{needle} (global) from the
\href{http://emboss.sourceforge.net/}{EMBOSS} suite (see above) and should
return the same results. The \verb|pairwise2| module has undergone some
optimization regarding speed and memory consumption recently (Biopython versions
\textgreater 1.67) so that for short sequences (global alignments:
\textasciitilde 2000 residues, local alignments \textasciitilde 600 residues)
it's faster (or equally fast) to use \verb|pairwise2| than calling EMBOSS' 
\texttt{water} or \texttt{needle} via the command line tools.

Suppose you want to do a global pairwise alignment between the same two
hemoglobin sequences from above (\texttt{HBA\_HUMAN}, \texttt{HBB\_HUMAN})
stored in \texttt{alpha.faa} and \texttt{beta.faa}:

%doctest examples
\begin{minted}{pycon}
>>> from Bio import pairwise2
>>> from Bio import SeqIO
>>> seq1 = SeqIO.read("alpha.faa", "fasta")
>>> seq2 = SeqIO.read("beta.faa", "fasta")
>>> alignments = pairwise2.align.globalxx(seq1.seq, seq2.seq)
\end{minted}

As you see, we call the alignment function with \verb|align.globalxx|. The tricky
part are the last two letters of the function name (here: \texttt{xx}), which are
used for  decoding the scores and penalties for matches (and mismatches) and gaps.
The first letter decodes the match score, e.g. \texttt{x} means that a match counts
1 while mismatches have no costs. With \texttt{m} general values for either matches
or mismatches can be defined
(for more options see \href{http://biopython.org/docs/1.77/api/Bio.pairwise2.html}{Biopython's API}).
The second letter decodes the cost for gaps; \texttt{x} means no gap costs at all,
with \texttt{s} different penalties for opening and extending a gap can be assigned.
So, \verb|globalxx| means that only matches between both sequences are counted.

Our variable \texttt{alignments} now contains a list of alignments (at least one) which
have the same optimal score for the given conditions. In our example this are 80
different alignments with the score 72 (\verb|Bio.pairwise2| will return up to 1000
alignments). Have a look at one of these alignments:

%cont-doctest
\begin{minted}{pycon}
>>> len(alignments)
80
>>> print(alignments[0]) # doctest:+ELLIPSIS
Alignment(seqA='MV-LSPADKTNV---K-A--A-WGKVGAHAG...YR-', seqB='MVHL-----T--PEEKSAVTALWGKV----...Y-H', score=72.0, start=0, end=217)
\end{minted}

Each alignment is a named tuple consisting of the two aligned sequences, the score, the
start and the end positions of the alignment (in global alignments the start is
always 0 and the end the length of the alignment). \verb|Bio.pairwise2| has a
function \verb|format_alignment| for a nicer printout:

%cont-doctest
\begin{minted}{pycon}
>>> print(pairwise2.format_alignment(*alignments[0])) # doctest:+ELLIPSIS
MV-LSPADKTNV---K-A--A-WGKVGAHAG---EY-GA-EALE-RMFLSF----PTTK-TY--F...YR-
|| |     |     | |  | ||||        |  |  |||  |  |      |    |   |...|  
MVHL-----T--PEEKSAVTALWGKV-----NVDE-VG-GEAL-GR--L--LVVYP---WT-QRF...Y-H
  Score=72
<BLANKLINE>
\end{minted}

Since Biopython 1.77 the required parameters can be supplied with keywords. The
last example can now also be written as:

%cont-doctest
\begin{minted}{pycon}
>>> alignments = pairwise2.align.globalxx(sequenceA=seq1.seq, sequenceB=seq2.seq)
\end{minted}

Better alignments are usually obtained by penalizing gaps: higher costs
for opening a gap and lower costs for extending an existing gap. For amino
acid sequences match scores are usually encoded in matrices like \texttt{PAM}
or \texttt{BLOSUM}. Thus, a more meaningful alignment for our example can be
obtained by using the BLOSUM62 matrix, together with a gap open penalty of 10
and a gap extension penalty of 0.5 (using \verb|globalds|):

\begin{minted}{pycon}
>>> from Bio import pairwise2
>>> from Bio import SeqIO
>>> from Bio.Align import substitution_matrices
>>> blosum62 = substitution_matrices.load("BLOSUM62")
>>> seq1 = SeqIO.read("alpha.faa", "fasta")
>>> seq2 = SeqIO.read("beta.faa", "fasta")
>>> alignments = pairwise2.align.globalds(seq1.seq, seq2.seq, blosum62, -10, -0.5)
>>> len(alignments)
2
>>> print(pairwise2.format_alignment(*alignments[0]))
MV-LSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTY...KYR
|| |.|..|..|.|.|||| ......|............|.......||.
MVHLTPEEKSAVTALWGKV-NVDEVGGEALGRLLVVYPWTQRFF...KYH
  Score=292.5

\end{minted}

This alignment has the same score that we obtained earlier with EMBOSS needle
using the same sequences and the same parameters.

Local alignments are called similarly with the function \verb|align.localXX|,
where again XX stands for a two letter code for the match and gap functions:

%doctest
\begin{minted}{pycon}
>>> from Bio import pairwise2
>>> from Bio.Align import substitution_matrices
>>> blosum62 = substitution_matrices.load("BLOSUM62")
>>> alignments = pairwise2.align.localds("LSPADKTNVKAA", "PEEKSAV", blosum62, -10, -1)
>>> print(pairwise2.format_alignment(*alignments[0]))
3 PADKTNV
  |..|..|
1 PEEKSAV
  Score=16
<BLANKLINE>
\end{minted}

In recent Biopython versions, \verb|format_alignment| will only print the 
aligned part of a local alignment (together with the start positions in 1-based
notation, as shown in the above example). If you are also interested in the non-
aligned parts of the sequences, use the keyword-parameter \verb|full_sequences=True|:

%doctest
\begin{minted}{pycon}
>>> from Bio import pairwise2
>>> from Bio.Align import substitution_matrices
>>> blosum62 = substitution_matrices.load("BLOSUM62")
>>> alignments = pairwise2.align.localds("LSPADKTNVKAA", "PEEKSAV", blosum62, -10, -1)
>>> print(pairwise2.format_alignment(*alignments[0], full_sequences=True))
LSPADKTNVKAA
  |..|..|   
--PEEKSAV---
  Score=16
<BLANKLINE>
\end{minted}

Note that local alignments must, as defined by Smith \& Waterman, have a 
positive score (\textgreater 0). Thus, \verb|pairwise2| may return no
alignments if no score \textgreater 0 has been obtained. Also, \verb|pairwise2|
will not report alignments which are the result of the addition of zero-scoring
extensions on either site. In the next example, the pairs serin/aspartate (S/D)
and lysin/asparagin (K/N) both have a match score of 0. As you see, the aligned
part has not been extended:

%doctest
\begin{minted}{pycon}
>>> from Bio import pairwise2
>>> from Bio.Align import substitution_matrices
>>> blosum62 = substitution_matrices.load("BLOSUM62")
>>> alignments = pairwise2.align.localds("LSSPADKTNVKKAA", "DDPEEKSAVNN", blosum62, -10, -1)
>>> print(pairwise2.format_alignment(*alignments[0]))
4 PADKTNV
  |..|..|
3 PEEKSAV
  Score=16
<BLANKLINE>
\end{minted}

Instead of supplying a complete match/mismatch matrix, the match code
\texttt{m} allows for easy defining general match/mismatch values. The next
example uses match/mismatch scores of 5/-4 and gap penalties (open/extend)
of 2/0.5 using \verb|localms|:

%cont-doctest
\begin{minted}{pycon}
>>> alignments = pairwise2.align.localms("AGAACT", "GAC", 5, -4, -2, -0.5)
>>> print(pairwise2.format_alignment(*alignments[0]))
2 GAAC
  | ||
1 G-AC
  Score=13
<BLANKLINE>
\end{minted}

One useful keyword argument of the \verb|Bio.pairwise2.align| functions is
\texttt{score\_only}. When set to \texttt{True} it will only return the score
of the best alignment(s), but in a significantly shorter time. It will also
allow the alignment of longer sequences before a memory error is raised.
Another useful keyword argument is \texttt{one\_alignment\_only=True} which
will also result in some speed gain.

Unfortunately, \verb|Bio.pairwise2| does not work with Biopython's multiple
sequence alignment objects (yet).
However, the module has some interesting advanced features: you can
define your own match and gap functions (interested in testing affine
logarithmic gap costs?), gap penalties and end gaps penalties can be different
for both sequences, sequences can be supplied as lists (useful if you have
residues that are encoded by more than one character), etc. These features
are hard (if at all) to realize with other alignment tools. For more details
see the modules documentation in
\href{http://biopython.org/docs/\bpversion/api/Bio.pairwise2.html}{Biopython's API}.

\subsection{PairwiseAligner}
\label{sec:pairwisealigner}
The new \verb|Bio.Align.PairwiseAligner| implements the Needleman-Wunsch, Smith-Waterman,
Gotoh (three-state), and Waterman-Smith-Beyer global and local pairwise alignment algorithms.
We refer to Durbin {\textit et al.} \cite{durbin1998} for in-depth information on sequence alignment algorithms.

\subsubsection{Basic usage}
\label{sec:pairwise-basic}

To generate pairwise alignments, first create a \verb+PairwiseAligner+ object:

%doctest examples
\begin{minted}{pycon}
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
\end{minted}
The \verb+PairwiseAligner+ object \verb+aligner+
(see Section~\ref{sec:pairwise-aligner})
stores the alignment parameters to be used for the pairwise alignments.

These attributes can be set in the constructor of the object or after the object
is made.

%cont-doctest
\begin{minted}{pycon}
>>> aligner = Align.PairwiseAligner(match_score=1.0)
\end{minted}

Or, equivalently:

%cont-doctest
\begin{minted}{pycon}
>>> aligner.match_score = 1.0
\end{minted}

Use the \verb+aligner.score+ method to calculate the alignment score between
two sequences:

%cont-doctest
\begin{minted}{pycon}
>>> seq1 = "GAACT"
>>> seq2 = "GAT"
>>> score = aligner.score(seq1, seq2)
>>> score
3.0
\end{minted}

To see the actual alignments, use the \verb+aligner.align+ method and iterate over the \verb+PairwiseAlignment+ objects returned:

%cont-doctest
\begin{minted}{pycon}
>>> alignments = aligner.align(seq1, seq2)
>>> for alignment in alignments:
...     print(alignment)
... 
GAACT
||--|
GA--T
<BLANKLINE>
GAACT
|-|-|
G-A-T
<BLANKLINE>
\end{minted}

By default, a global pairwise alignment is performed, which finds the optimal
alignment over the whole length of \verb+seq1+ and \verb+seq2+.
Instead, a local alignment will find the subsequence of
\verb+seq1+ and \verb+seq2+ with the highest alignment score.
Local alignments can be generated by setting \verb+aligner.mode+ to
\verb+"local"+:

%cont-doctest
\begin{minted}{pycon}
>>> aligner.mode = 'local'
>>> seq1 = "AGAACTC"
>>> seq2 = "GAACT"
>>> score = aligner.score(seq1, seq2)
>>> score
5.0
>>> alignments = aligner.align(seq1, seq2)
>>> for alignment in alignments:
...     print(alignment)
...
AGAACTC
 ||||| 
 GAACT 
<BLANKLINE>
\end{minted}

Note that there is some ambiguity in the definition of the best local alignments if segments with a score 0 can be added to the alignment. We follow the suggestion by Waterman \& Eggert \cite{waterman1987} and disallow such extensions.

\subsubsection{The pairwise aligner object}
\label{sec:pairwise-aligner}

The \verb+PairwiseAligner+ object stores all alignment parameters to be used
for the pairwise alignments. To see an overview of the values for all parameters, use

%cont-doctest
\begin{minted}{pycon}
>>> print(aligner)
Pairwise sequence aligner with parameters
  match_score: 1.000000
  mismatch_score: 0.000000
  target_internal_open_gap_score: 0.000000
  target_internal_extend_gap_score: 0.000000
  target_left_open_gap_score: 0.000000
  target_left_extend_gap_score: 0.000000
  target_right_open_gap_score: 0.000000
  target_right_extend_gap_score: 0.000000
  query_internal_open_gap_score: 0.000000
  query_internal_extend_gap_score: 0.000000
  query_left_open_gap_score: 0.000000
  query_left_extend_gap_score: 0.000000
  query_right_open_gap_score: 0.000000
  query_right_extend_gap_score: 0.000000
  mode: local
<BLANKLINE>
\end{minted}
See Sections~\ref{sec:pairwise-substitution-scores}, \ref{sec:pairwise-affine-gapscores}, and \ref{sec:pairwise-general-gapscores} below for the definition of these
parameters. The attribute \verb+mode+ (described above in Section~\ref{sec:pairwise-basic}) can be set equal to \verb+"global"+ or \verb+"local"+ to specify global or local pairwise alignment, respectively.

Depending on the gap scoring parameters
(see Sections~\ref{sec:pairwise-affine-gapscores} and
\ref{sec:pairwise-general-gapscores}) and mode, a \verb+PairwiseAligner+ object
automatically chooses the appropriate algorithm to use for pairwise sequence alignment. To verify the selected algorithm, use

%cont-doctest
\begin{minted}{pycon}
>>> aligner.algorithm
'Smith-Waterman'
\end{minted}
This attribute is read-only.

A \verb+PairwiseAligner+ object also stores the precision $\epsilon$ to be used during alignment. The value of $\epsilon$ is stored in the attribute \verb+aligner.epsilon+, and by default is equal to $10^{-6}$:


%cont-doctest
\begin{minted}{pycon}
>>> aligner.epsilon
1e-06
\end{minted}
Two scores will be considered equal to each other for the purpose of the alignment if the absolute difference between them is less than $\epsilon$.

\subsubsection{Substitution scores}
\label{sec:pairwise-substitution-scores}

Substitution scores define the value to be added to the total score when two letters (nucleotides or amino acids) are aligned to each other. The substitution scores to be used by the \verb+PairwiseAligner+ can be specified in two ways:

\begin{itemize}
\item By specifying a match score for identical letters, and a mismatch scores for mismatched letters. Nucleotide sequence alignments are typically based on match and mismatch scores. For example, by default BLAST \cite{altschul1990} uses a match score of $+1$ and a mismatch score of $-2$ for nucleotide alignments by \verb+megablast+, with a gap penalty of 2.5 (see section \ref{sec:pairwise-affine-gapscores} for more information on gap scores). Match and mismatch scores can be specified by setting the \verb+match+ and \verb+mismatch+ attributes of the \verb+PairwiseAligner+ object:

%doctest examples lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
>>> aligner.match_score
1.0
>>> aligner.mismatch_score
0.0
>>> score = aligner.score("ACGT","ACAT")
>>> print(score)
3.0
>>> aligner.match_score = 1.0
>>> aligner.mismatch_score = -2.0
>>> aligner.gap_score = -2.5
>>> score = aligner.score("ACGT","ACAT")
>>> print(score)
1.0
\end{minted}
When using match and mismatch scores, the character \verb+X+ is interpreted as an unknown character and gets a zero score in alignments, irrespective of the value of the match or mismatch score:
%cont-doctest
\begin{minted}{pycon}
>>> score = aligner.score("ACGT","ACXT")
>>> print(score)
3.0
\end{minted}
\item
Alternatively, you can use the \verb+substitution_matrix+ attribute of the \verb+PairwiseAligner+ object to specify a substitution matrix. This allows you to apply different scores for different pairs of matched and mismatched letters. This is typically used for amino acid sequence alignments. For example, by default BLAST \cite{altschul1990} uses the BLOSUM62 substitution matrix for protein alignments by \verb+blastp+. This substitution matrix is available from Biopython:

%cont-doctest
\begin{minted}{pycon}
>>> from Bio.Align import substitution_matrices
>>> substitution_matrices.load()  #doctest: +ELLIPSIS
['BENNER22', 'BENNER6', 'BENNER74', 'BLOSUM45', 'BLOSUM50', 'BLOSUM62', ..., 'TRANS']
>>> matrix = substitution_matrices.load("BLOSUM62")
>>> print(matrix)  #doctest: +ELLIPSIS
#  Matrix made by matblas from blosum62.iij
...
     A    R    N    D    C    Q ...
A  4.0 -1.0 -2.0 -2.0  0.0 -1.0 ...
R -1.0  5.0  0.0 -2.0 -3.0  1.0 ...
N -2.0  0.0  6.0  1.0 -3.0  0.0 ...
D -2.0 -2.0  1.0  6.0 -3.0  0.0 ...
C  0.0 -3.0 -3.0 -3.0  9.0 -3.0 ...
Q -1.0  1.0  0.0  0.0 -3.0  5.0 ...
...
>>> aligner.substitution_matrix = matrix
>>> score = aligner.score("ACDQ", "ACDQ")
>>> score
24.0
>>> score = aligner.score("ACDQ", "ACNQ")
>>> score
19.0
\end{minted}
When using a substitution matrix, \verb+X+ is {\em not} interpreted as an unknown character. Instead, the score provided by the substutition matrix will be used:

%cont-doctest
\begin{minted}{pycon}
>>> matrix['D','X']
-1.0
>>> score = aligner.score("ACDQ", "ACXQ")
>>> score
17.0
\end{minted}
\end{itemize}

By default, \verb+aligner.substitution_matrix+ is \verb+None+.
The attributes \verb+aligner.match_score+ and \verb+aligner.mismatch_score+ are
ignored if \verb+aligner.substitution_matrix+ is not \verb+None+.
Setting \verb+aligner.match_score+ or \verb+aligner.mismatch_score+ to valid values will reset \verb+aligner.substitution_matrix+ to \verb+None+.
 
\subsubsection{Affine gap scores}
\label{sec:pairwise-affine-gapscores}

Affine gap scores are defined by a score to open a gap, and a score to extend
an existing gap:

$\textrm{gap score} = \textrm{open gap score} + (n-1) \times \textrm{extend gap score}$,

where $n$ is the length of the gap.
Biopython's pairwise sequence aligner allows fine-grained control over the gap
scoring scheme by specifying the following twelve attributes of a \verb+PairwiseAligner+ object:

\begin{table}[h]
\begin{tabular}{|l|l|}
\hline
\bf{Opening scores}                   & \bf{Extending scores} \\
\hline
\verb+query_left_open_gap_score+      & \verb+query_left_extend_gap_score+ \\
\verb+query_internal_open_gap_score+  & \verb+query_internal_extend_gap_score+ \\
\verb+query_right_open_gap_score+     & \verb+query_right_extend_gap_score+ \\
\verb+target_left_open_gap_score+     & \verb+target_left_extend_gap_score+ \\
\verb+target_internal_open_gap_score+ & \verb+target_internal_extend_gap_score+ \\
\verb+target_right_open_gap_score+    & \verb+target_right_extend_gap_score+ \\
\hline
\end{tabular}
\end{table}

These attributes allow for different gap scores for internal gaps and on either end of the sequence, as shown in this example:

\begin{table}[h]
\begin{tabular}{|c|c|l|}
\hline
\bf{target} & \bf{query} & \bf{score} \\
\hline
A & - &  query left open gap score \\
C & - &  query left extend gap score \\
C & - &  query left extend gap score \\
G & G &  match score \\
G & T &  mismatch score \\
G & - &  query internal open gap score \\
A & - &  query internal extend gap score \\
A & - &  query internal extend gap score \\
T & T &  match score \\
A & A &  match score \\
G & - &  query internal open gap score \\
C & C &  match score \\
- & C &  target internal open gap score \\
- & C &  target internal extend gap score \\
C & C &  match score \\
T & G &  mismatch score \\
C & C &  match score \\
- & C &  target internal open gap score \\
A & A &  match score \\
- & T &  target right open gap score \\
- & A &  target right extend gap score \\
- & A &  target right extend gap score \\
\hline
\end{tabular}
\end{table}

For convenience, \verb+PairwiseAligner+ objects have additional attributes that refer to a number of these values collectively, as shown (hierarchically) in Table~\ref{table:align-meta-attributes}.

\begin{table}
\caption{Meta-attributes of the pairwise aligner objects.}
\begin{tabular}{|l|l|}
\hline
\bf{Meta-attribute} & \bf{Attributes it maps to} \\
\hline
\verb+gap_score+ & \verb+target_gap_score+, \verb+query_gap_score+ \\
\verb+open_gap_score+ & \verb+target_open_gap_score+, \verb+query_open_gap_score+ \\
\verb+extend_gap_score+ & \verb+target_extend_gap_score+, \verb+query_extend_gap_score+ \\
\verb+internal_gap_score+ & \verb+target_internal_gap_score+, \verb+query_internal_gap_score+ \\
\verb+internal_open_gap_score+ & \verb+target_internal_open_gap_score+, \verb+query_internal_open_gap_score+ \\
\verb+internal_extend_gap_score+ & \verb+target_internal_extend_gap_score+, \verb+query_internal_extend_gap_score+ \\
\verb+end_gap_score+ & \verb+target_end_gap_score+, \verb+query_end_gap_score+ \\
\verb+end_open_gap_score+ & \verb+target_end_open_gap_score+, \verb+query_end_open_gap_score+ \\
\verb+end_extend_gap_score+ & \verb+target_end_extend_gap_score+, \verb+query_end_extend_gap_score+ \\
\verb+left_gap_score+ & \verb+target_left_gap_score+, \verb+query_left_gap_score+ \\
\verb+right_gap_score+ & \verb+target_right_gap_score+, \verb+query_right_gap_score+ \\
\verb+left_open_gap_score+ & \verb+target_left_open_gap_score+, \verb+query_left_open_gap_score+ \\
\verb+left_extend_gap_score+ & \verb+target_left_extend_gap_score+, \verb+query_left_extend_gap_score+ \\
\verb+right_open_gap_score+ & \verb+target_right_open_gap_score+, \verb+query_right_open_gap_score+ \\
\verb+right_extend_gap_score+ & \verb+target_right_extend_gap_score+, \verb+query_right_extend_gap_score+ \\
\verb+target_open_gap_score+ & \verb+target_internal_open_gap_score+, \verb+target_left_open_gap_score+, \\
                             & \verb+target_right_open_gap_score+ \\
\verb+target_extend_gap_score+ & \verb+target_internal_extend_gap_score+, \verb+target_left_extend_gap_score+, \\
                               & \verb+target_right_extend_gap_score+ \\
\verb+target_gap_score+ & \verb+target_open_gap_score+, \verb+target_extend_gap_score+ \\
\verb+query_open_gap_score+ & \verb+query_internal_open_gap_score+, \verb+query_left_open_gap_score+, \\
                            & \verb+query_right_open_gap_score+ \\
\verb+query_extend_gap_score+ & \verb+query_internal_extend_gap_score+, \verb+query_left_extend_gap_score+, \\
                              & \verb+query_right_extend_gap_score+ \\
\verb+query_gap_score+ & \verb+query_open_gap_score+, \verb+query_extend_gap_score+ \\
\verb+target_internal_gap_score+ & \verb+target_internal_open_gap_score+, \verb+target_internal_extend_gap_score+ \\
\verb+target_end_gap_score+ & \verb+target_end_open_gap_score+, \verb+target_end_extend_gap_score+ \\
\verb+target_end_open_gap_score+ & \verb+target_left_open_gap_score+, \verb+target_right_open_gap_score+ \\
\verb+target_end_extend_gap_score+ & \verb+target_left_extend_gap_score+, \verb+target_right_extend_gap_score+ \\
\verb+target_left_gap_score+ & \verb+target_left_open_gap_score+, \verb+target_left_extend_gap_score+ \\
\verb+target_right_gap_score+ & \verb+target_right_open_gap_score+, \verb+target_right_extend_gap_score+ \\
\verb+query_end_gap_score+ & \verb+query_end_open_gap_score+, \verb+query_end_extend_gap_score+ \\
\verb+query_end_open_gap_score+ & \verb+query_left_open_gap_score+, \verb+query_right_open_gap_score+ \\
\verb+query_end_extend_gap_score+ & \verb+query_left_extend_gap_score+, \verb+query_right_extend_gap_score+ \\
\verb+query_internal_gap_score+ & \verb+query_internal_open_gap_score+, \verb+query_internal_extend_gap_score+ \\
\verb+query_left_gap_score+ & \verb+query_left_open_gap_score+, \verb+query_left_extend_gap_score+ \\
\verb+query_right_gap_score+ & \verb+query_right_open_gap_score+, \verb+query_right_extend_gap_score+ \\
\hline
\end{tabular}
\label{table:align-meta-attributes}
\end{table}

\subsubsection{General gap scores}
\label{sec:pairwise-general-gapscores}

For even more fine-grained control over the gap scores, you can specify a gap scoring function. For example, the gap scoring function below disallows a gap after two nucleotides in the query sequence:

%doctest
\begin{minted}{pycon}
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
>>> def my_gap_score_function(start, length):
...     if start==2:
...         return -1000
...     else:
...         return -1 * length
...
>>> aligner.query_gap_score = my_gap_score_function
>>> alignments = aligner.align("AACTT", "AATT")
>>> for alignment in alignments:
...     print(alignment)
... 
AACTT
-|.||
-AATT
<BLANKLINE>
AACTT
|-.||
A-ATT
<BLANKLINE>
AACTT
||.-|
AAT-T
<BLANKLINE>
AACTT
||.|-
AATT-
<BLANKLINE>
\end{minted}

\subsubsection{Iterating over alignments}

The \verb+alignments+ returned by \verb+aligner.align+ are a kind of immutable iterable objects (similar to \verb+range+). While they appear similarto a \verb+tuple+ or \verb+list+ of \verb+PairwiseAlignment+ objects, they are different in the sense that each \verb+PairwiseAlignment+ object is created dynamically when it is needed. This approach was chosen because the number of alignments can be extremely large, in particular for poor alignments (see Section~\ref{sec:pairwise-examples} for an example).

You can perform the following operations on \verb+alignments+:
\begin{itemize}
\item \verb+len(alignments)+ returns the number of alignments stored. This function returns quickly, even if the number of alignments is huge. If the number of alignments is extremely large (typically, larger than 9,223,372,036,854,775,807, which is the largest integer that can be stored as a \verb+long int+ on 64 bit machines), \verb+len(alignments)+ will raise an \verb+OverflowError+. A large number of alignments suggests that the alignment quality is low.

%doctest
\begin{minted}{pycon}
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
>>> alignments = aligner.align("AAA", "AA")
>>> len(alignments)
3
\end{minted}
\item You can extract a specific alignment by index:

%doctest
\begin{minted}{pycon}
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
>>> alignments = aligner.align("AAA", "AA")
>>> print(alignments[2])
AAA
-||
-AA
<BLANKLINE>
>>> print(alignments[0])
AAA
||-
AA-
<BLANKLINE>
\end{minted}
\item You can iterate over alignments, for example as in
\begin{minted}{pycon}
>>> for alignment in alignments:
...     print(alignment)
...
\end{minted}
Note that \verb+alignments+ can be reused, i.e. you can iterate over alignments multiple times:

%doctest
\begin{minted}{pycon}
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
>>> alignments = aligner.align("AAA", "AA")
>>> for alignment in alignments:
...     print(alignment)
...
AAA
||-
AA-
<BLANKLINE>
AAA
|-|
A-A
<BLANKLINE>
AAA
-||
-AA
<BLANKLINE>
>>> for alignment in alignments:
...     print(alignment)
...
AAA
||-
AA-
<BLANKLINE>
AAA
|-|
A-A
<BLANKLINE>
AAA
-||
-AA
<BLANKLINE>
\end{minted}
You can also convert the \verb+alignments+ iterator into a \verb+list+ or \verb+tuple+:
\begin{minted}{pycon}
>>> alignments = list(alignments)
\end{minted}
It is wise to check the number of alignments by calling \verb+len(alignments)+ before attempting to call \verb+list(alignments)+ to save all alignments as a list.
\item The alignment score (which has the same value for each alignment in \verb+alignments+) is stored as an attribute. This allows you to check the alignment score before proceeding to extract individual alignments:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignments.score)
2.0
\end{minted}
\end{itemize}

\subsubsection{Alignment objects}
The \verb+aligner.align+ method returns \verb+PairwiseAlignment+ objects, each representing one alignment between the two sequences.

%doctest
\begin{minted}{pycon}
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
>>> seq1 = "GAACT"
>>> seq2 = "GAT"
>>> alignments = aligner.align(seq1, seq2)
>>> alignment = alignments[0]
>>> alignment # doctest: +SKIP
<Bio.Align.PairwiseAlignment object at 0x10204d250>
\end{minted}

Each alignment stores the alignment score:

%cont-doctest
\begin{minted}{pycon}
>>> alignment.score
3.0
\end{minted}
as well as pointers to the sequences that were aligned:

%cont-doctest
\begin{minted}{pycon}
>>> alignment.target
'GAACT'
>>> alignment.query
'GAT'
\end{minted}

Print the \verb+PairwiseAlignment+ object to show the alignment explicitly:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment)
GAACT
||--|
GA--T
<BLANKLINE>
\end{minted}

You can also represent the alignment as a string in PSL (Pattern Space Layout, as generated by BLAT \cite{kent2002}) format:

%cont-doctest
\begin{minted}{pycon}
>>> format(alignment, 'psl')
'3\t0\t0\t0\t0\t0\t1\t2\t+\tquery\t3\t0\t3\ttarget\t5\t0\t5\t2\t2,1,\t0,2,\t0,4,\n'
\end{minted}

Use the \verb+aligned+ property to find the start and end indices of subsequences in the target and query sequence that were aligned to each other.
Generally, if the alignment between target (t) and query (q) consists of $N$
chunks, you get two tuples of length $N$:

\begin{minted}{python}
(
    ((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}

In the current example, `alignment.aligned` returns two tuples of length 2:

%cont-doctest
\begin{minted}{pycon}
>>> alignment.aligned
(((0, 2), (4, 5)), ((0, 2), (2, 3)))
\end{minted}
while for the alternative alignment, two tuples of length 3 are returned:

%cont-doctest
\begin{minted}{pycon}
>>> alignment = alignments[1]
>>> print(alignment)
GAACT
|-|-|
G-A-T
<BLANKLINE>
>>> alignment.aligned
(((0, 1), (2, 3), (4, 5)), ((0, 1), (1, 2), (2, 3)))
\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}
>>> aligner.mismatch_score = -10
>>> alignments = aligner.align("AAACAAA", "AAAGAAA")
>>> len(alignments)
2
>>> print(alignments[0])
AAAC-AAA
|||--|||
AAA-GAAA
<BLANKLINE>
>>> alignments[0].aligned
(((0, 3), (4, 7)), ((0, 3), (4, 7)))
>>> print(alignments[1])
AAA-CAAA
|||--|||
AAAG-AAA
<BLANKLINE>
>>> alignments[1].aligned
(((0, 3), (4, 7)), ((0, 3), (4, 7)))
\end{minted}
The \verb+aligned+ property can be used to identify alignments that are identical to each other in terms of their aligned sequences.

\subsubsection{Examples}
\label{sec:pairwise-examples}

Suppose you want to do a global pairwise alignment between the same two
hemoglobin sequences from above (\texttt{HBA\_HUMAN}, \texttt{HBB\_HUMAN})
stored in \texttt{alpha.faa} and \texttt{beta.faa}:

%doctest examples
\begin{minted}{pycon}
>>> from Bio import Align
>>> from Bio import SeqIO
>>> seq1 = SeqIO.read("alpha.faa", "fasta")
>>> seq2 = SeqIO.read("beta.faa", "fasta")
>>> aligner = Align.PairwiseAligner()
>>> score = aligner.score(seq1.seq, seq2.seq)
>>> print(score)
72.0
\end{minted}

showing an alignment score of 72.0. To see the individual alignments, do

%cont-doctest
\begin{minted}{pycon}
>>> alignments = aligner.align(seq1.seq, seq2.seq)
\end{minted}
In this example, the total number of optimal alignments is huge (more than $4 \times 10^{37}$), and calling \verb+len(alignments)+ will raise an \verb+OverflowError+:

% don't include in the doctest, as 32-bit system show a different number
\begin{minted}{pycon}
>>> len(alignments)
Traceback (most recent call last):
...
OverflowError: number of optimal alignments is larger than 9223372036854775807
\end{minted}
Let's have a look at the first alignment:

%cont-doctest
\begin{minted}{pycon}
>>> alignment = alignments[0]
\end{minted}

The alignment object stores the alignment score, as well as the alignment
itself:

%cont-doctest
\begin{minted}{pycon}
>>> print(alignment.score)
72.0
>>> print(alignment)  #doctest: +ELLIPSIS
MV-LS-PAD--KTN--VK-AA-WGKV-----GAHAGEYGAEALE-RMFLSF----P-TTKTY--FPHF--...
||-|--|----|----|--|--||||-----|---||--|--|--|--|------|-|------|--|--...
MVHL-TP--EEK--SAV-TA-LWGKVNVDEVG---GE--A--L-GR--L--LVVYPWT----QRF--FES...
\end{minted}

Better alignments are usually obtained by penalizing gaps: higher costs
for opening a gap and lower costs for extending an existing gap. For amino
acid sequences match scores are usually encoded in matrices like \texttt{PAM}
or \texttt{BLOSUM}. Thus, a more meaningful alignment for our example can be
obtained by using the BLOSUM62 matrix, together with a gap open penalty of 10
and a gap extension penalty of 0.5:

%doctest examples lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> from Bio import SeqIO
>>> from Bio.Align import substitution_matrices
>>> seq1 = SeqIO.read("alpha.faa", "fasta")
>>> seq2 = SeqIO.read("beta.faa", "fasta")
>>> aligner = Align.PairwiseAligner()
>>> aligner.open_gap_score = -10
>>> aligner.extend_gap_score = -0.5
>>> aligner.substitution_matrix = substitution_matrices.load("BLOSUM62")
>>> score = aligner.score(seq1.seq, seq2.seq)
>>> print(score)
292.5
>>> alignments = aligner.align(seq1.seq, seq2.seq)
>>> len(alignments)
2
>>> print(alignments[0].score)
292.5
>>> print(alignments[0])  #doctest: +ELLIPSIS
MV-LSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHF-DLS-----HGSAQVKGHGKKV...
||-|.|..|..|.|.||||--...|.|.|||.|.....|.|...|..|-|||-----.|...||.|||||...
MVHLTPEEKSAVTALWGKV--NVDEVGGEALGRLLVVYPWTQRFFESFGDLSTPDAVMGNPKVKAHGKKV...
<BLANKLINE>
\end{minted}

This alignment has the same score that we obtained earlier with EMBOSS needle
using the same sequences and the same parameters.

To perform a local alignment, set \verb+aligner.mode+ to \verb+'local'+:

%cont-doctest
\begin{minted}{pycon}
>>> aligner.mode = 'local'
>>> aligner.open_gap_score = -10
>>> aligner.extend_gap_score = -1
>>> alignments = aligner.align("LSPADKTNVKAA", "PEEKSAV")
>>> print(len(alignments))
1
>>> alignment = alignments[0]
>>> print(alignment)
LSPADKTNVKAA
  |..|..|   
  PEEKSAV   
<BLANKLINE>
>>> print(alignment.score)
16.0
\end{minted}

\subsubsection{Generalized pairwise alignments}
\label{sec:generalized-pairwise}

In most cases, \verb+PairwiseAligner+ is used to perform alignments of sequences (strings or \verb+Seq+ objects) consisting of single-letter nucleotides or amino acids. More generally, \verb+PairwiseAligner+ can also be applied to lists or tuples of arbitrary objects. This section will describe some examples of such generalized pairwise alignments.

\paragraph*{Generalized pairwise alignments using a substitution matrix and alphabet}

Schneider \textit{et al.} \cite{schneider2005} created a substitution matrix for aligning three-nucleotide codons (see \hyperlink{codonmatrix}{below} in section \ref{sec:substitution_matrices} for more information). This substitution matrix is associated with an alphabet consisting of all three-letter codons:

%doctest . lib:numpy
\begin{minted}{pycon}
>>> from Bio.Align import substitution_matrices
>>> m = substitution_matrices.load("SCHNEIDER")
>>> m.alphabet  #doctest: +ELLIPSIS
('AAA', 'AAC', 'AAG', 'AAT', 'ACA', 'ACC', 'ACG', 'ACT', ..., 'TTG', 'TTT')
\end{minted}
We can use this matrix to align codon sequences to each other:

%cont-doctest
\begin{minted}{pycon}
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
>>> aligner.substitution_matrix = m
>>> aligner.gap_score = -1.0
>>> s1 = ('AAT', 'CTG', 'TTT', 'TTT')
>>> s2 = ('AAT', 'TTA', 'TTT')
>>> alignments = aligner.align(s1, s2)
>>> len(alignments)
2
>>> print(alignments[0])
AAT CTG TTT TTT
||| ... ||| ---
AAT TTA TTT ---
<BLANKLINE>
>>> print(alignments[1])
AAT CTG TTT TTT
||| ... --- |||
AAT TTA --- TTT
<BLANKLINE>
\end{minted}
Note that aligning \verb+TTT+ to \verb+TTA+, as in this example:
\begin{minted}{pycon}
AAT CTG TTT TTT
||| --- ... |||
AAT --- TTA TTT
\end{minted}
would get a much lower score:

%cont-doctest
\begin{minted}{pycon}
>>> print(m['CTG', 'TTA'])
7.6
>>> print(m['TTT', 'TTA'])
-0.3
\end{minted}
presumably because \verb+CTG+ and \verb+TTA+ both code for leucine, while \verb+TTT+ codes for phenylalanine. The three-letter codon substitution matrix also reveals a preference among codons representing the same amino acid. For example, \verb+TTA+ has a preference for \verb+CTG+ preferred compared to \verb+CTC+, though all three code for leucine:

%cont-doctest
\begin{minted}{pycon}
>>> s1 = ('AAT', 'CTG', 'CTC', 'TTT')
>>> s2 = ('AAT', 'TTA', 'TTT')
>>> alignments = aligner.align(s1, s2)
>>> len(alignments)
1
>>> print(alignments[0])
AAT CTG CTC TTT
||| ... --- |||
AAT TTA --- TTT
<BLANKLINE>
>>> print(m['CTC', 'TTA'])
6.5
\end{minted}

\paragraph*{Generalized pairwise alignments using match/mismatch scores and an alphabet}

Using the three-letter amino acid symbols, the sequences above translate to

%doctest
\begin{minted}{pycon}
>>> s1 = ('Asn', 'Leu', 'Leu', 'Phe')
>>> s2 = ('Asn', 'Leu', 'Phe')
\end{minted}
We can align these sequences directly to each other by using a three-letter amino acid alphabet:

%cont-doctest
\begin{minted}{pycon}
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
>>> aligner.alphabet = ['Ala', 'Arg', 'Asn', 'Asp', 'Cys',
...                     'Gln', 'Glu', 'Gly', 'His', 'Ile',
...                     'Leu', 'Lys', 'Met', 'Phe', 'Pro',
...                     'Ser', 'Thr', 'Trp', 'Tyr', 'Val']
\end{minted}
We use +6/-1 match and mismatch scores as an approximation of the BLOSUM62 matrix, and align these sequences to each other:

%cont-doctest
\begin{minted}{pycon}
>>> aligner.match = +6
>>> aligner.mismatch = -1
>>> alignments = aligner.align(s1, s2)
>>> print(len(alignments))
2
>>> print(alignments[0])
Asn Leu Leu Phe
||| ||| --- |||
Asn Leu --- Phe
<BLANKLINE>
>>> print(alignments[1])
Asn Leu Leu Phe
||| --- ||| |||
Asn --- Leu Phe
<BLANKLINE>
>>> print(alignments.score)
18.0
\end{minted}

\paragraph*{Generalized pairwise alignments using match/mismatch scores and integer sequences}

Internally, the first step when performing an alignment is to replace the two sequences by integer arrays consisting of the indices of each letter in each sequence in the alphabet associated with the aligner. This step can be bypassed by passing integer arrays directly:

%doctest . lib:numpy
\begin{minted}{pycon}
>>> import numpy
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
>>> s1 = numpy.array([2, 10, 10, 13], numpy.int32)
>>> s2 = numpy.array([2, 10, 13], numpy.int32)
>>> aligner.match = +6
>>> aligner.mismatch = -1
>>> alignments = aligner.align(s1, s2)
>>> print(len(alignments))
2
>>> print(alignments[0])
2 10 10 13
| || -- ||
2 10 -- 13
<BLANKLINE>
>>> print(alignments[1])
2 10 10 13
| -- || ||
2 -- 10 13
<BLANKLINE>
>>> print(alignments.score)
18.0
\end{minted}
Note that the indices should consist of 32-bit integers, as specified in this example by \verb+numpy.int32+.

Negative indices are interpreted as unknown letters, and receive a zero score:

%cont-doctest
\begin{minted}{pycon}
>>> s2 = numpy.array([2, -5, 13], numpy.int32)
>>> aligner.gap_score = -3
>>> alignments = aligner.align(s1, s2)
>>> print(len(alignments))
2
>>> print(alignments[0])
2 10 10 13
| .. -- ||
2 -5 -- 13
<BLANKLINE>
>>> print(alignments[1])
2 10 10 13
| -- .. ||
2 -- -5 13
<BLANKLINE>
>>> print(alignments.score)
9.0
\end{minted}

\paragraph*{Generalized pairwise alignments using a substitution matrix and integer sequences}

Integer sequences can also be aligned using a substitution matrix, in this case a numpy square array without an alphabet associated with it. In this case, all index values must be non-negative, and smaller than the size of the substitution matrix:

%doctest . lib:numpy
\begin{minted}{pycon}
>>> from Bio import Align
>>> import numpy
>>> aligner = Align.PairwiseAligner()
>>> m = numpy.eye(5)
>>> m[0, 1:] = m[1:, 0] = -2
>>> m[2,2] = 3
>>> print(m)
[[ 1. -2. -2. -2. -2.]
 [-2.  1.  0.  0.  0.]
 [-2.  0.  3.  0.  0.]
 [-2.  0.  0.  1.  0.]
 [-2.  0.  0.  0.  1.]]
>>> aligner.substitution_matrix = m
>>> aligner.gap_score = -1
>>> s1 = numpy.array([0, 2, 3, 4], numpy.int32)
>>> s2 = numpy.array([0, 3, 2, 1], numpy.int32)
>>> alignments = aligner.align(s1, s2)
>>> print(len(alignments))
2
>>> print(alignments[0])
0 - 2 3 4
| - | . -
0 3 2 1 -
<BLANKLINE>
>>> print(alignments[1])
0 - 2 3 4
| - | - .
0 3 2 - 1
<BLANKLINE>
>>> print(alignments.score)
2.0
\end{minted}

\section{Substitution matrices}
\label{sec:substitution_matrices}

The \verb+Array+ class in \verb+Bio.Align.substitution_matrices+ is a subclass of numpy arrays that supports indexing both by integers and by specific strings. An \verb+Array+ instance can either be a one-dimensional array or a square two-dimensional arrays. A one-dimensional \verb+Array+ object can for example be used to store the nucleotide frequency of a DNA sequence, while a two-dimensional \verb+Array+ object can be used to represent a scoring matrix for sequence alignments.

\subsection*{Creating an Array object}

To create a one-dimensional \verb+Array+, only the alphabet of allowed letters needs to be specified:

%doctest . lib:numpy
\begin{minted}{pycon}
>>> from Bio.Align.substitution_matrices import Array
>>> counts = Array("ACGT")
>>> print(counts)
A 0.0
C 0.0
G 0.0
T 0.0
<BLANKLINE>
\end{minted}
The allowed letters are stored in the \verb+alphabet+ property:

%cont-doctest
\begin{minted}{pycon}
>>> counts.alphabet
'ACGT'
\end{minted}
This property is read-only; modifying the underlying \verb+_alphabet+ attribute may lead to unexpected results.
Elements can be accessed both by letter and by integer index:

%cont-doctest
\begin{minted}{pycon}
>>> counts['C'] = -3
>>> counts[2] = 7
>>> print(counts)
A  0.0
C -3.0
G  7.0
T  0.0
<BLANKLINE>
>>> counts[1]
-3.0
\end{minted}

Using a letter that is not in the alphabet, or an index that is out of bounds, will cause a \verb+IndexError+:

%cont-doctest
\begin{minted}{pycon}
>>> counts['U']
Traceback (most recent call last):
    ...
IndexError: 'U'
>>> counts['X'] = 6
Traceback (most recent call last):
    ...
IndexError: 'X'
>>> counts[7]
Traceback (most recent call last):
    ...
IndexError: index 7 is out of bounds for axis 0 with size 4
\end{minted}

A two-dimensional \verb+Array+ can be created by specifying \verb+dims=2+:

%doctest . lib:numpy
\begin{minted}{pycon}
>>> from Bio.Align.substitution_matrices import Array
>>> counts = Array("ACGT", dims=2)
>>> print(counts)
    A   C   G   T
A 0.0 0.0 0.0 0.0
C 0.0 0.0 0.0 0.0
G 0.0 0.0 0.0 0.0
T 0.0 0.0 0.0 0.0
<BLANKLINE>
\end{minted}
Again, both letters and integers can be used for indexing, and specifying a letter that is not in the alphabet will cause an \verb+IndexError+:

%cont-doctest
\begin{minted}{pycon}
>>> counts['A', 'C'] = 12.0
>>> counts[2, 1] = 5.0
>>> counts[3, 'T'] = -2
>>> print(counts)
    A    C   G    T
A 0.0 12.0 0.0  0.0
C 0.0  0.0 0.0  0.0
G 0.0  5.0 0.0  0.0
T 0.0  0.0 0.0 -2.0
<BLANKLINE>
>>> counts['X', 1]
Traceback (most recent call last):
    ...
IndexError: 'X'
>>> counts['A', 5]
Traceback (most recent call last):
    ...
IndexError: index 5 is out of bounds for axis 1 with size 4
\end{minted}
Selecting a row or column from the two-dimensional array will return a one-dimensional \verb+Array+:

%cont-doctest
\begin{minted}{pycon}
>>> counts = Array("ACGT", dims=2)
>>> counts['A', 'C'] = 12.0
>>> counts[2, 1] = 5.0
>>> counts[3, 'T'] = -2
\end{minted}
% don't include this in the doctest, as the exact output is platform-dependent
\begin{minted}{pycon}
>>> counts['G']
Array([0., 5., 0., 0.],
      alphabet='ACGT')
>>> counts[:, 'C']
Array([12.,  0.,  5.,  0.],
      alphabet='ACGT')
\end{minted}

\verb+Array+ objects can thus be used as an array and as a dictionary. They can be converted to plain numpy arrays or plain dictionary objects:

%cont-doctest
\begin{minted}{pycon}
>>> import numpy
>>> x = Array("ACGT")
>>> x['C'] = 5
\end{minted}
% don't include this in the doctest, as the exact output is platform-dependent
\begin{minted}{pycon}
>>> x
Array([0., 5., 0., 0.],
      alphabet='ACGT')
>>> a = numpy.array(x)  # create a plain numpy array
>>> a
array([0., 5., 0., 0.])
>>> d = dict(x)  # create a plain dictionary
>>> d
{'A': 0.0, 'C': 5.0, 'G': 0.0, 'T': 0.0}
\end{minted}

While the alphabet of an \verb+Array+ is usually a string, you may also use a tuple of (immutable) objects. This is used for example for a \hyperlink{codonmatrix}{codon substitution matrix}, where the keys are not individual nucleotides or amino acids but instead three-nucleotide codons.

While the \verb+alphabet+ property of an \verb+Array+ is immutable, you can create a new \verb+Array+ object by selecting the letters you are interested in from the alphabet. For example,
%cont-doctest
\begin{minted}{pycon}
>>> a = Array("ABCD", dims=2, data=numpy.arange(16).reshape(4,4))
>>> print(a)
     A    B    C    D
A  0.0  1.0  2.0  3.0
B  4.0  5.0  6.0  7.0
C  8.0  9.0 10.0 11.0
D 12.0 13.0 14.0 15.0
<BLANKLINE>
>>> b = a.select("CAD")
>>> print(b)
     C    A    D
C 10.0  8.0 11.0
A  2.0  0.0  3.0
D 14.0 12.0 15.0
<BLANKLINE>
\end{minted}
Note that this also allows you to reorder the alphabet.

Data for letters that are not found in the alphabet are set to zero:
%cont-doctest
\begin{minted}{pycon}
>>> c = a.select("DEC")
>>> print(c)
     D   E    C
D 15.0 0.0 14.0
E  0.0 0.0  0.0
C 11.0 0.0 10.0
<BLANKLINE>
\end{minted}

\subsection*{Calculating a substitution matrix from a pairwise sequence alignment}

As \verb+Array+ is a subclass of a numpy array, you can apply mathematical operations on an \verb+Array+ object in much the same way. Here, we illustrate this by calculating a scoring matrix from the alignment of the 16S ribosomal RNA gene sequences of {\it Escherichia coli} and {\it Bacillus subtilis}. First, we create a \verb+PairwiseAligner+ and initialize it with the default scores used by \verb+blastn+:

%doctest ../Tests/Align lib:numpy
\begin{minted}{pycon}
>>> from Bio.Align import PairwiseAligner
>>> aligner = PairwiseAligner()
>>> aligner.mode = 'local'
>>> aligner.match_score = 2
>>> aligner.mismatch_score = -3
>>> aligner.open_gap_score = -7
>>> aligner.extend_gap_score = -2
\end{minted}
Next, we read in the 16S ribosomal RNA gene sequence of {\it Escherichia coli} and {\it Bacillus subtilis} (provided in \verb+Tests/scoring_matrices/ecoli.fa+ and \verb+Tests/scoring_matrices/bsubtilis.fa+), and align them to each other:

%cont-doctest
\begin{minted}{pycon}
>>> from Bio import SeqIO
>>> sequence1 = SeqIO.read('ecoli.fa', 'fasta')
>>> sequence2 = SeqIO.read('bsubtilis.fa', 'fasta')
>>> alignments = aligner.align(sequence1.seq, sequence2.seq)
\end{minted}
The number of alignments generated is very large:

%cont-doctest
\begin{minted}{pycon}
>>> len(alignments)
1990656
\end{minted}
However, as they only differ trivially from each other, we arbitrarily choose the first alignment, and count the number of each substitution:

%cont-doctest
\begin{minted}{pycon}
>>> alignment = alignments[0]
>>> from Bio.Align.substitution_matrices import Array
>>> frequency = Array("ACGT", dims=2)
>>> for (start1, end1), (start2, end2) in zip(*alignment.aligned):
...     seq1 = sequence1[start1:end1]
...     seq2 = sequence2[start2:end2]
...     for c1, c2 in zip(seq1, seq2):
...         frequency[c1, c2] += 1
...
>>> print(frequency)
      A     C     G     T
A 307.0  19.0  34.0  19.0
C  15.0 280.0  25.0  29.0
G  34.0  24.0 401.0  20.0
T  24.0  36.0  20.0 228.0
<BLANKLINE>
\end{minted}
We normalize against the total number to find the probability of each substitution, and create a symmetric matrix:

%cont-doctest
\begin{minted}{pycon}
>>> import numpy
>>> probabilities = frequency / numpy.sum(frequency)
>>> probabilities = (probabilities + probabilities.transpose()) / 2.0
>>> print(format(probabilities, "%.4f"))
       A      C      G      T
A 0.2026 0.0112 0.0224 0.0142
C 0.0112 0.1848 0.0162 0.0215
G 0.0224 0.0162 0.2647 0.0132
T 0.0142 0.0215 0.0132 0.1505
<BLANKLINE>
\end{minted}
The background probability is the probability of finding an A, C, G, or T nucleotide in each sequence separately. This can be calculated as the sum of each row or column:

%cont-doctest
\begin{minted}{pycon}
>>> background = numpy.sum(probabilities, 0)
>>> print(format(background, "%.4f"))
A 0.2505
C 0.2337
G 0.3165
T 0.1993
<BLANKLINE>
\end{minted}
The number of substitutions expected at random is simply the product of the background distribution with itself:

%cont-doctest
\begin{minted}{pycon}
>>> expected = numpy.dot(background[:,None], background[None, :])
>>> print(format(expected, "%.4f"))
       A      C      G      T
A 0.0627 0.0585 0.0793 0.0499
C 0.0585 0.0546 0.0740 0.0466
G 0.0793 0.0740 0.1002 0.0631
T 0.0499 0.0466 0.0631 0.0397
<BLANKLINE>
\end{minted}
The scoring matrix can then be calculated as the logarithm of the odds-ratio of the observed and the expected probabilities:

%cont-doctest
\begin{minted}{pycon}
>>> oddsratios = probabilities / expected
>>> scoring_matrix = numpy.log2(oddsratios)
>>> print(scoring_matrix)
     A    C    G    T
A  1.7 -2.4 -1.8 -1.8
C -2.4  1.8 -2.2 -1.1
G -1.8 -2.2  1.4 -2.3
T -1.8 -1.1 -2.3  1.9
<BLANKLINE>
\end{minted}
The matrix can be used to set the substitution matrix for the pairwise aligner:

%cont-doctest
\begin{minted}{pycon}
>>> aligner.substitution_matrix = scoring_matrix
\end{minted}

A \verb+ValueError+ is triggered if the \verb+Array+ objects appearing in a mathematical operation have different alphabets:

%doctest . lib:numpy
\begin{minted}{pycon}
>>> from Bio.Align.substitution_matrices import Array
>>> d = Array("ACGT")
>>> r = Array("ACGU")
>>> d + r
Traceback (most recent call last):
    ...
ValueError: alphabets are inconsistent
\end{minted}

\subsection*{Reading \texttt{Array} object from file}

\verb+Bio.Align.substitution_matrices+ includes a parser to read one- and two-dimensional \verb+Array+ objects from file. One-dimensional arrays are represented by a simple two-column format, with the first column containing the key and the second column the corresponding value. For example, the file \verb+hg38.chrom.sizes+ (obtained from UCSC), available in the \verb+Tests/Align+ subdirectory of the Biopython distribution, contains the size in nucleotides of each chromosome in human genome assembly hg38:
\begin{minted}{text}
chr1    248956422
chr2    242193529
chr3    198295559
chr4    190214555
...
chrUn_KI270385v1    990
chrUn_KI270423v1    981
chrUn_KI270392v1    971
chrUn_KI270394v1    970
\end{minted}
To parse this file, use

%doctest ../Tests/Align lib:numpy
\begin{minted}{pycon}
>>> from Bio.Align import substitution_matrices
>>> with open("hg38.chrom.sizes") as handle:
...    table = substitution_matrices.read(handle)
...
>>> print(table)  #doctest: +ELLIPSIS
chr1 248956422.0
chr2 242193529.0
chr3 198295559.0
chr4 190214555.0
...
chrUn_KI270423v1       981.0
chrUn_KI270392v1       971.0
chrUn_KI270394v1       970.0
<BLANKLINE>
\end{minted}
Use \verb+dtype=int+ to read the values as integers:

%cont-doctest
\begin{minted}{pycon}
>>> with open("hg38.chrom.sizes") as handle:
...    table = substitution_matrices.read(handle, int)
...
>>> print(table)  #doctest: +ELLIPSIS
chr1 248956422
chr2 242193529
chr3 198295559
chr4 190214555
...
chrUn_KI270423v1       981
chrUn_KI270392v1       971
chrUn_KI270394v1       970
<BLANKLINE>
\end{minted}

For two-dimensional arrays, we follow the file format of substitution matrices provided by NCBI. For example, the BLOSUM62 matrix, which is the default substitution matrix for NCBI's protein-protein BLAST \cite{altschul1990} program \verb+blastp+, is stored as follows:
\begin{minted}{text}
#  Matrix made by matblas from blosum62.iij
#  * column uses minimum score
#  BLOSUM Clustered Scoring Matrix in 1/2 Bit Units
#  Blocks Database = /data/blocks_5.0/blocks.dat
#  Cluster Percentage: >= 62
#  Entropy =   0.6979, Expected =  -0.5209
   A  R  N  D  C  Q  E  G  H  I  L  K  M  F  P  S  T  W  Y  V  B  Z  X  *
A  4 -1 -2 -2  0 -1 -1  0 -2 -1 -1 -1 -1 -2 -1  1  0 -3 -2  0 -2 -1  0 -4 
R -1  5  0 -2 -3  1  0 -2  0 -3 -2  2 -1 -3 -2 -1 -1 -3 -2 -3 -1  0 -1 -4 
N -2  0  6  1 -3  0  0  0  1 -3 -3  0 -2 -3 -2  1  0 -4 -2 -3  3  0 -1 -4 
D -2 -2  1  6 -3  0  2 -1 -1 -3 -4 -1 -3 -3 -1  0 -1 -4 -3 -3  4  1 -1 -4 
C  0 -3 -3 -3  9 -3 -4 -3 -3 -1 -1 -3 -1 -2 -3 -1 -1 -2 -2 -1 -3 -3 -2 -4 
Q -1  1  0  0 -3  5  2 -2  0 -3 -2  1  0 -3 -1  0 -1 -2 -1 -2  0  3 -1 -4 
E -1  0  0  2 -4  2  5 -2  0 -3 -3  1 -2 -3 -1  0 -1 -3 -2 -2  1  4 -1 -4 
G  0 -2  0 -1 -3 -2 -2  6 -2 -4 -4 -2 -3 -3 -2  0 -2 -2 -3 -3 -1 -2 -1 -4 
H -2  0  1 -1 -3  0  0 -2  8 -3 -3 -1 -2 -1 -2 -1 -2 -2  2 -3  0  0 -1 -4 
...
\end{minted}
This file is included in the Biopython distribution under \verb+Bio/Align/substitution_matrices/data+. To parse this file, use

%doctest ../Bio/Align/substitution_matrices/data lib:numpy
\begin{minted}{pycon}
>>> from Bio.Align import substitution_matrices
>>> with open("BLOSUM62") as handle:
...    matrix = substitution_matrices.read(handle)
...
>>> print(matrix.alphabet)
ARNDCQEGHILKMFPSTWYVBZX*
>>> print(matrix['A','D'])
-2.0
\end{minted}
The header lines starting with \verb+#+ are stored in the attribute \verb+header+:

%cont-doctest
\begin{minted}{pycon}
>>> matrix.header[0]
'Matrix made by matblas from blosum62.iij'
\end{minted}
We can now use this matrix as the substitution matrix on an aligner object:

%cont-doctest
\begin{minted}{pycon}
>>> from Bio.Align import PairwiseAligner
>>> aligner = PairwiseAligner()
>>> aligner.substitution_matrix = matrix
\end{minted}
To save an Array object, create a string first:

%cont-doctest
\begin{minted}{pycon}
>>> text = format(matrix)
>>> print(text)  #doctest: +ELLIPSIS
#  Matrix made by matblas from blosum62.iij
#  * column uses minimum score
#  BLOSUM Clustered Scoring Matrix in 1/2 Bit Units
#  Blocks Database = /data/blocks_5.0/blocks.dat
#  Cluster Percentage: >= 62
#  Entropy =   0.6979, Expected =  -0.5209
     A    R    N    D    C    Q    E    G    H    I    L    K    M    F    P    S ...
A  4.0 -1.0 -2.0 -2.0  0.0 -1.0 -1.0  0.0 -2.0 -1.0 -1.0 -1.0 -1.0 -2.0 -1.0  1.0 ...
R -1.0  5.0  0.0 -2.0 -3.0  1.0  0.0 -2.0  0.0 -3.0 -2.0  2.0 -1.0 -3.0 -2.0 -1.0 ...
N -2.0  0.0  6.0  1.0 -3.0  0.0  0.0  0.0  1.0 -3.0 -3.0  0.0 -2.0 -3.0 -2.0  1.0 ...
D -2.0 -2.0  1.0  6.0 -3.0  0.0  2.0 -1.0 -1.0 -3.0 -4.0 -1.0 -3.0 -3.0 -1.0  0.0 ...
C  0.0 -3.0 -3.0 -3.0  9.0 -3.0 -4.0 -3.0 -3.0 -1.0 -1.0 -3.0 -1.0 -2.0 -3.0 -1.0 ...
...
\end{minted}
and write the \verb+text+ to a file.

\subsection*{Loading predefined substitution matrices}

Biopython contains a large set of substitution matrices defined in the literature, including BLOSUM (Blocks Substitution Matrix) \cite{henikoff1992} and PAM (Point Accepted Mutation) matrices \cite{dayhoff1978}. These matrices are available as flat files in the \verb+Bio/Align/scoring_matrices/data+ directory, and can be loaded into Python using the \verb+load+ function in the \verb+scoring_matrices+ submodule. For example, the BLOSUM62 matrix can be loaded by running

%doctest . lib:numpy
\begin{minted}{pycon}
>>> from Bio.Align import substitution_matrices
>>> m = substitution_matrices.load("BLOSUM62")
\end{minted}
This substitution matrix has an alphabet consisting of the 20 amino acids used in the genetic code, the three ambiguous amino acids B (asparagine or aspartic acid), Z (glutamine or glutamic acid), and X (representing any amino acid), and the stop codon represented by an asterisk:

%cont-doctest
\begin{minted}{pycon}
>>> m.alphabet
'ARNDCQEGHILKMFPSTWYVBZX*'
\end{minted}

To get a full list of available substitution matrices, use \verb+load+ without an argument:

%cont-doctest
\begin{minted}{pycon}
>>> substitution_matrices.load()  #doctest: +ELLIPSIS
['BENNER22', 'BENNER6', 'BENNER74', 'BLOSUM45', 'BLOSUM50', ..., 'TRANS']
\end{minted}

\hypertarget{codonmatrix}
Note that the substitution matrix provided by Schneider \textit{et al.} \cite{schneider2005} uses an alphabet consisting of three-nucleotide codons:

%cont-doctest
\begin{minted}{pycon}
>>> m = substitution_matrices.load("SCHNEIDER")
>>> m.alphabet  #doctest: +ELLIPSIS
('AAA', 'AAC', 'AAG', 'AAT', 'ACA', 'ACC', 'ACG', 'ACT', ..., 'TTG', 'TTT')
\end{minted}
