File: chapter_align.tex

package info (click to toggle)
python-biopython 1.78%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 65,756 kB
  • sloc: python: 221,141; xml: 178,777; ansic: 13,369; sql: 1,208; makefile: 131; sh: 70
file content (3022 lines) | stat: -rw-r--r-- 118,657 bytes parent folder | download
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
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
\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}