File: chapter_align.tex

package info (click to toggle)
python-biopython 1.68%2Bdfsg-3~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 46,856 kB
  • sloc: python: 160,306; xml: 93,216; ansic: 9,118; sql: 1,208; makefile: 155; sh: 63
file content (1537 lines) | stat: -rw-r--r-- 66,119 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
\chapter{Multiple Sequence Alignment objects}
\label{chapter:Bio.AlignIO}

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 {\it 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 {\it 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.

A further optional \verb|alphabet| argument allowing you to specify the expected alphabet. This can be useful as many alignment file formats do not explicitly label the sequences as RNA, DNA or protein -- which means \verb|Bio.AlignIO| will default to using a generic alphabet.

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

\begin{verbatim}
# 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{verbatim}

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{http://pfam.sanger.ac.uk/}.  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{verbatim}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
\end{verbatim}

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

%cont-doctest
\begin{verbatim}
>>> print(alignment)
SingleLetterAlphabet() 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{verbatim}

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{verbatim}
>>> 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{verbatim}

You could also use the alignment object's \verb|format| method to show it in a particular file format  -- see Section~\ref{sec:alignment-format-method} 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{verbatim}
>>> 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{verbatim}

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

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

Sanger provide a nice web interface at \url{http://pfam.sanger.ac.uk/family?acc=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{verbatim}
>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{verbatim}

\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{verbatim}
from Bio import AlignIO
alignment = AlignIO.read("PF05371_seed.faa", "fasta")
print(alignment)
\end{verbatim}

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/DIST/docs/api/Bio.AlignIO-module.html}{online}):

\begin{verbatim}
>>> from Bio import AlignIO
>>> help(AlignIO)
...
\end{verbatim}

\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{verbatim}
    5    6
Alpha     AACAAC
Beta      AACCCC
Gamma     ACCAAC
Delta     CCACCA
Epsilon   CCAAAC
\end{verbatim}

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{verbatim}
    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{verbatim}

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

%TODO - Replace the print blank line with print()?
\begin{verbatim}
from Bio import AlignIO
alignments = AlignIO.parse("resampled.phy", "phylip")
for alignment in alignments:
    print(alignment)
    print("")
\end{verbatim}

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

\begin{verbatim}
SingleLetterAlphabet() alignment with 5 rows and 6 columns
AAACCA Alpha
AAACCC Beta
ACCCCA Gamma
CCCAAC Delta
CCCAAA Epsilon

SingleLetterAlphabet() alignment with 5 rows and 6 columns
AAACAA Alpha
AAACCC Beta
ACCCAA Gamma
CCCACC Delta
CCCAAA Epsilon

SingleLetterAlphabet() alignment with 5 rows and 6 columns
AAAAAC Alpha
AAACCC Beta
AACAAC Gamma
CCCCCA Delta
CCCAAC Epsilon

...

SingleLetterAlphabet() alignment with 5 rows and 6 columns
AAAACC Alpha
ACCCCC Beta
AAAACC Gamma
CCCCAA Delta
CAAACC Epsilon
\end{verbatim}

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{verbatim}
from Bio import AlignIO
alignments = list(AlignIO.parse("resampled.phy", "phylip"))
last_align = alignments[-1]
first_align = alignments[0]
\end{verbatim}

\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{verbatim}
>Alpha
ACTACGACTAGCTCAG--G
>Beta
ACTACCGCTAGCTCAGAAG
>Gamma
ACTACGGCTAGCACAGAAG
>Alpha
ACTACGACTAGCTCAGG--
>Beta
ACTACCGCTAGCTCAGAAG
>Gamma
ACTACGGCTAGCACAGAAG
\end{verbatim}

\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{verbatim}
>Alpha
ACTACGACTAGCTCAG--G
>Beta
ACTACCGCTAGCTCAGAAG
>Alpha
ACTACGACTAGCTCAGG--
>Gamma
ACTACGGCTAGCACAGAAG
>Alpha
ACTACGACTAGCTCAGG--
>Delta
ACTACGGCTAGCACAGAAG
\end{verbatim}

\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{verbatim}
>Alpha
ACTACGACTAGCTCAG--G
>XXX
ACTACCGCTAGCTCAGAAG
>Alpha
ACTACGACTAGCTCAGG
>YYY
ACTACGGCAAGCACAGG
>Alpha
--ACTACGAC--TAGCTCAGG
>ZZZ
GGACTACGACAATAGCTCAGG
\end{verbatim}

\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:

%TODO - Replace the print blank line with print()?
\begin{verbatim}
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{verbatim}

\noindent giving:

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

Alignment length 17
ACTACGACTAGCTCAGG - Alpha
ACTACGGCAAGCACAGG - YYY

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

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.

\begin{verbatim}
from Bio.Alphabet import generic_dna
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Align import MultipleSeqAlignment

align1 = MultipleSeqAlignment([
             SeqRecord(Seq("ACTGCTAGCTAG", generic_dna), id="Alpha"),
             SeqRecord(Seq("ACT-CTAGCTAG", generic_dna), id="Beta"),
             SeqRecord(Seq("ACTGCTAGDTAG", generic_dna), id="Gamma"),
         ])

align2 = MultipleSeqAlignment([
             SeqRecord(Seq("GTCAGC-AG", generic_dna), id="Delta"),
             SeqRecord(Seq("GACAGCTAG", generic_dna), id="Epsilon"),
             SeqRecord(Seq("GTCAGCTAG", generic_dna), id="Zeta"),
         ])

align3 = MultipleSeqAlignment([
             SeqRecord(Seq("ACTAGTACAGCTG", generic_dna), id="Eta"),
             SeqRecord(Seq("ACTAGTACAGCT-", generic_dna), id="Theta"),
             SeqRecord(Seq("-CTACTACAGGTG", generic_dna), id="Iota"),
         ])

my_alignments = [align1, align2, align3]
\end{verbatim}

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

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

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

\begin{verbatim}
 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{verbatim}

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{verbatim}
from Bio import AlignIO
count = AlignIO.convert("PF05371_seed.sth", "stockholm", "PF05371_seed.aln", "clustal")
print("Converted %i alignments" % count)
\end{verbatim}

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

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

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{verbatim}
from Bio import AlignIO
alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
AlignIO.write([alignment], "PF05371_seed.aln", "clustal")
\end{verbatim}

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

\begin{verbatim}
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{verbatim}

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

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

This time the output looks like this:

\begin{verbatim}
 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{verbatim}

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{verbatim}
from Bio import AlignIO
AlignIO.convert("PF05371_seed.sth", "stockholm", "PF05371_seed.phy", "phylip-relaxed")
\end{verbatim}

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

\begin{verbatim}
 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{verbatim}

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

\begin{verbatim}
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)

AlignIO.write([alignment], "PF05371_seed.phy", "phylip")
\end{verbatim}

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

\noindent Here is the new (strict) PHYLIP format output:
\begin{verbatim}
 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{verbatim}

\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-method}
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 take advantage of the alignment object's \verb|format()| method.
This takes a single mandatory argument, a lower case string which is supported by \verb|Bio.AlignIO| as an output format.  For example:

\begin{verbatim}
from Bio import AlignIO
alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
print(alignment.format("clustal"))
\end{verbatim}

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 the \verb|format()| method is using the \verb|StringIO| string based handle and calling
\verb|Bio.AlignIO.write()|.  You can do this in your own code if for example you are using an
older version of Biopython:

\begin{verbatim}
from Bio import AlignIO
from StringIO import StringIO

alignments = AlignIO.parse("PF05371_seed.sth", "stockholm")

out_handle = StringIO()
AlignIO.write(alignments, out_handle, "clustal")
clustal_data = out_handle.getvalue()

print(clustal_data)
\end{verbatim}

\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{verbatim}
>>> 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{verbatim}

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{verbatim}
>>> print(alignment)
SingleLetterAlphabet() 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])
SingleLetterAlphabet() 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{verbatim}

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{verbatim}
>>> print(alignment[2, 6])
T
\end{verbatim}

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

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

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

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

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{verbatim}
>>> print(alignment[3:6, :6])
SingleLetterAlphabet() alignment with 3 rows and 6 columns
AEGDDP COATB_BPM13/24-72
AEGDDP COATB_BPZJ2/1-49
AEGDDP Q9T0Q9_BPFD/1-49
\end{verbatim}

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

%cont-doctest
\begin{verbatim}
>>> print(alignment[:, :6])
SingleLetterAlphabet() 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{verbatim}

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{verbatim}
>>> print(alignment[:, 6:9])
SingleLetterAlphabet() 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{verbatim}

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

%cont-doctest
\begin{verbatim}
>>> print(alignment[:, 9:])
SingleLetterAlphabet() 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{verbatim}

\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{verbatim}
>>> edited = alignment[:, :6] + alignment[:, 9:]
>>> print(edited)
SingleLetterAlphabet() 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{verbatim}

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{verbatim}
>>> edited.sort()
>>> print(edited)
SingleLetterAlphabet() 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{verbatim}

\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:

%This example fails under PyPy 2.0, https://bugs.pypy.org/issue1546
%doctest examples lib:numpy
\begin{verbatim}
>>> 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{verbatim}

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

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

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{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 (see Section~\ref{sec:pairwise2}), which is supplemented by
functions written in C for speed enhancements. 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:Bio.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:

\begin{verbatim}
>>> import Bio.Align.Applications
>>> dir(Bio.Align.Applications)
...
['ClustalwCommandline', 'DialignCommandline', 'MafftCommandline', 'MuscleCommandline',
'PrankCommandline', 'ProbconsCommandline', 'TCoffeeCommandline' ...]
\end{verbatim}

\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{seq: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{verbatim}
>>> from Bio.Align.Applications import ClustalwCommandline
>>> help(ClustalwCommandline)
...
\end{verbatim}

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{verbatim}
>>> from Bio.Align.Applications import ClustalwCommandline
>>> cline = ClustalwCommandline("clustalw2", infile="opuntia.fasta")
>>> print(cline)
clustalw2 -infile=opuntia.fasta
\end{verbatim}

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{verbatim}
>>> 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{verbatim}
%Don't run it in the doctest
\begin{verbatim}
>>> assert os.path.isfile(clustalw_exe), "Clustal W executable missing"
>>> stdout, stderr = clustalw_cline()
\end{verbatim}

\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{verbatim}
>>> from Bio import AlignIO
>>> align = AlignIO.read("opuntia.aln", "clustal")
>>> print(align)
SingleLetterAlphabet() 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{verbatim}

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{verbatim}
>>> 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{verbatim}

\noindent Chapter \ref{sec: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{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> help(MuscleCommandline)
...
\end{verbatim}

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{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.txt")
>>> print(cline)
muscle -in opuntia.fasta -out opuntia.txt
\end{verbatim}

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{verbatim}
>>> 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{verbatim}

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

%doctest
\begin{verbatim}
>>> 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{verbatim}

\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{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
>>> print(muscle_cline)
muscle -in opuntia.fasta
\end{verbatim}

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{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
>>> stdout, stderr = muscle_cline()
>>> from StringIO import StringIO
>>> from Bio import AlignIO
>>> align = AlignIO.read(StringIO(stdout), "fasta")
>>> print(align)
SingleLetterAlphabet() 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{verbatim}

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{verbatim}
>>> 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)
SingleLetterAlphabet() 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{verbatim}

\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{verbatim}
>>> from Bio import SeqIO
>>> records = (r for r in SeqIO.parse("opuntia.fasta", "fasta") if len(r) < 900)
\end{verbatim}

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{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(clwstrict=True)
>>> print(muscle_cline)
muscle -clwstrict
\end{verbatim}

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

\begin{verbatim}
>>> 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{verbatim}

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

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

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{verbatim}
>>> from Bio import AlignIO
>>> align = AlignIO.read(child.stdout, "clustal")
>>> print(align)
SingleLetterAlphabet() 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{verbatim}

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,
Python 2 versus Python 3), 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{verbatim}
>>> from Bio import SeqIO
>>> records = (r for r in SeqIO.parse("opuntia.fasta", "fasta") if len(r) < 900)
>>> from StringIO import StringIO
>>> handle = StringIO()
>>> SeqIO.write(records, handle, "fasta")
6
>>> data = handle.getvalue()
\end{verbatim}

\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{verbatim}
>>> stdout, stderr = muscle_cline(stdin=data)
>>> from Bio import AlignIO
>>> align = AlignIO.read(StringIO(stdout), "clustal")
>>> print(align)
SingleLetterAlphabet() 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{verbatim}

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{seq: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{verbatim}
>HBA_HUMAN
MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHG
KKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTP
AVHASLDKFLASVSTVLTSKYR
\end{verbatim}

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

\begin{verbatim}
>HBB_HUMAN
MVHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQRFFESFGDLSTPDAVMGNPK
VKAHGKKVLGAFSDGLAHLDNLKGTFATLSELHCDKLHVDPENFRLLGNVLVCVLAHHFG
KEFTPPVQAAYQKVVAGVANALAHKYH
\end{verbatim}

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{verbatim}
>>> 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{verbatim}

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{verbatim}
>>> 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{verbatim}

\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{verbatim}
>>> from Bio.Emboss.Applications import NeedleCommandline
>>> help(NeedleCommandline)
...
\end{verbatim}

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

%doctest
\begin{verbatim}
>>> 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{verbatim}

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{verbatim}
>>> stdout, stderr = needle_cline()
>>> print(stdout + stderr)
Needleman-Wunsch global alignment of two sequences
\end{verbatim}

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

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

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.

\subsection{Biopython's pairwise2}
\label{sec:pairwise2}
Biopython has its own module to make local and global pairwise alignments,
\verb|Bio.pairwise2|. This module 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.

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{verbatim}
>>> 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{verbatim}

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/DIST/docs/api/Bio.pairwise2-module.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{verbatim}
>>> len(alignments)
80
\end{verbatim}
%This has been abbreviated, can't use as doctest
\begin{verbatim}
>>> print(alignments[0])
('MV-LSPADKTNV---K-A--A-WGKVGAHAG...YR-', 'MVHL-----T--PEEKSAVTALWGKV----...Y-H',
72.0, 0, 217)
\end{verbatim}

Each alignment is a 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:

%This has been abbreviated, can't use as doctest
\begin{verbatim}
>>> print(pairwise2.format_alignment(*alignment[0]))
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
\end{verbatim}

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|):

%doctest examples
\begin{verbatim}
>>> from Bio import pairwise2
>>> from Bio import SeqIO
>>> from Bio.SubsMat.MatrixInfo import 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
\end{verbatim}
%This has been abbreviated, can't use as doctest
\begin{verbatim}
>>> print(pairwise2.format_alignment(*alignments[0]))
MV-LSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTY...KYR
||||||||||||||||||||||||||||||||||||||||||||...|||
MVHLTPEEKSAVTALWGKV-NVDEVGGEALGRLLVVYPWTQRFF...KYH
  Score=292.5
\end{verbatim}

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{verbatim}
>>> from Bio import pairwise2
>>> from Bio.SubsMat.MatrixInfo import blosum62
>>> alignments = pairwise2.align.localds("LSPADKTNVKAA", "PEEKSAV", blosum62, -10, -1)
>>> print(pairwise2.format_alignment(*alignments[0]))
LSPADKTNVKAA
  |||||||
--PEEKSAV---
  Score=16
<BLANKLINE>
\end{verbatim}

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{verbatim}
>>> alignments = pairwise2.align.localms("AGAACT", "GAC", 5, -4, -2, -0.5)
>>> print(pairwise2.format_alignment(*alignments[0]))
AGAACT
 ||||
-G-AC-
  Score=13
<BLANKLINE>
\end{verbatim}

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.

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/DIST/docs/api/Bio.pairwise2-module.html}{Biopython's API}.