~ubuntu-branches/ubuntu/dapper/bioperl/dapper

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
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
#!/usr/bin/perl
# $Id: bptutorial.pl,v 1.133 2003/12/16 02:57:24 bosborne Exp $

=head1 NAME

BioPerlTutorial - a tutorial for bioperl

=head1 VERSION

1.2.3

=head1 AUTHOR

  Written by Peter Schattner <schattner@alum.mit.edu>

  Copyright Peter Schattner

  Contributions, additions and corrections have been made
  to this document by the following individuals:

  Jason Stajich
  Heikki Lehvaslaiho
  Brian Osborne
  Hilmar Lapp
  Chris Dagdigian
  Elia Stupka
  Ewan Birney

=head1 DESCRIPTION

   This tutorial includes "snippets" of code and text from various
   Bioperl documents including module documentation, example scripts
   and "t" test scripts. You may distribute this tutorial under the
   same terms as perl itself.

   This document is written in Perl POD (plain old documentation)
   format. You can run this file through your favorite pod translator
   (pod2html, pod2man, pod2text, etc.) if you would like a more
   convenient formatting.

  Table of Contents

  I. Introduction
  I.1 Overview
  I.2 Quick getting started scripts
  I.3 Software requirements
    I.3.1 For minimal bioperl installation
    I.3.2 For complete installation
  I.4 Installation procedures
  I.5 Additional comments for non-unix users
  I.6 Places to look for additional documentation

  II. Brief overview to bioperl's objects
  II.1 Sequence objects (Seq, PrimarySeq, LocatableSeq, RelSegment, LiveSeq, LargeSeq, RichSeq, SeqWithQuality, SeqI)
  II.2 Location objects (Simple, Split, Fuzzy)
  II.3 Interface objects and implementation objects

  III. Using bioperl
  III.1 Accessing sequence data from local and remote databases
    III.1.1 Accessing remote databases (Bio::DB::GenBank, etc)
    III.1.2 Indexing and accessing local databases (Bio::Index::*, bp_index.pl, bp_fetch.pl)
  III.2 Transforming formats of database/ file records
    III.2.1 Transforming sequence files (SeqIO)
    III.2.2 Transforming alignment files (AlignIO)
  III.3 Manipulating sequences
    III.3.1 Manipulating sequence data with Seq methods (Seq)
    III.3.2 Obtaining basic sequence statistics (SeqStats,SeqWord)
    III.3.3 Identifying restriction enzyme sites (Bio::Restriction)
    III.3.4 Identifying amino acid cleavage sites (Sigcleave)
    III.3.5 Miscellaneous sequence utilities: OddCodes, SeqPattern
    III.3.6 Converting coordinate systems (Coordinate::Pair, RelSegment)
  III.4 Searching for similar sequences
    III.4.1 Running BLAST remotely (using RemoteBlast.pm)
    III.4.2 Parsing BLAST and FASTA reports with Search and SearchIO
    III.4.3 Parsing BLAST reports with BPlite, BPpsilite, and BPbl2seq
    III.4.4 Parsing HMM reports (HMMER::Results, SearchIO)
    III.4.5 Running BLAST locally (StandAloneBlast)
  III.5 Manipulating sequence alignments (SimpleAlign)
  III.6 Searching for genes and other structures on genomic DNA (Genscan, Sim4, ESTScan, MZEF, Grail, Genemark, EPCR)
  III.7 Developing machine readable sequence annotations
    III.7.1 Representing sequence annotations (SeqFeature,RichSeq,Location)
    III.7.2 Representing sequence annotations (Annotation::Collection)
    III.7.3 Representing large sequences (LargeSeq)
    III.7.4 Representing changing sequences (LiveSeq)
    III.7.5 Representing related sequences - mutations, polymorphisms (Allele, SeqDiff)
    III.7.6 Incorporating quality data in sequence annotation (SeqWithQuality)
    III.7.7 Sequence XML representations - generation and parsing (SeqIO::game)
    III.7.8 Representing Sequence Features using GFF (Bio:Tools:GFF)
  III.8 Manipulating clusters of sequences (Cluster, ClusterIO)
  III.9 Representing non-sequence data in Bioperl: structures, trees, maps, graphics and bibliographic text
    III.9.1 Using 3D structure objects and reading PDB files (StructureI, Structure::IO)
    III.9.2 Tree objects and phylogenetic trees (Tree::Tree, TreeIO, PAML.pm )
    III.9.3 Map objects for manipulating genetic maps (Map::MapI, MapIO)
    III.9.4 Bibliographic objects for querying bibliographic databases (Biblio)
    III.9.5 Graphics objects for representing sequence objects as images (Graphics)
  III.10 Bioperl alphabets
    III.10.1 Extended DNA / RNA alphabet
    III.10.2 Amino Acid alphabet

  IV. Auxiliary Bioperl Libraries (Bioperl-run, Bioperl-db, etc.)
    IV.1 Using the Bioperl Auxiliary Libraries
    IV.2 Running programs (Bioperl-run and Bioperl-ext)
      IV.2.1 Sequence manipulation using the Bioperl EMBOSS and PISE interfaces
      IV.2.2 Aligning 2 sequences with Blast using  bl2seq and AlignIO
      IV.2.3 Aligning multiple sequences (Clustalw.pm, TCoffee.pm)
      IV.2.4 Aligning 2 sequences with Smith-Waterman (pSW)
    IV.3 Bioperl-db and BioSQL
    IV.4 Other Bioperl auxiliary libraries

  V. Appendices
    V.1 Finding out which methods are used by which Bioperl Objects
    V.2 Tutorial Demo Scripts

=head1 I. Introduction

=head2 I.1 Overview

Bioperl is a collection of perl modules that facilitate the
development of perl scripts for bioinformatics applications.  As
such, it does not include ready to use programs in the sense that many
commercial packages and free web-based interfaces do (e.g. Entrez, SRS).
On the other hand, bioperl does provide reusable perl modules that
facilitate writing perl scripts for sequence manipulation, accessing
of databases using a range of data formats and execution and parsing
of the results of various molecular biology programs including Blast,
clustalw, TCoffee, genscan, ESTscan and HMMER.  Consequently, bioperl
enables developing scripts that can analyze large quantities of
sequence data in ways that are typically difficult or impossible with
web based systems.

In order to take advantage of bioperl, the user needs a basic
understanding of the perl programming language including an
understanding of how to use perl references, modules, objects and
methods. If these concepts are unfamiliar the user is referred to any
of the various introductory or intermediate books on perl. We've liked
S. Holzmer's Perl Core Language, Coriolis Technology Press, for
example.  This tutorial is not intended to teach the fundamentals of
perl to those with little or no experience in the perl language.  On
the other hand, advanced knowledge of perl - such as how to write a
object-oriented perl module - is not required for successfully using bioperl.

Bioperl is open source software that is still under active
development.  The advantages of open source software are well known.
They include the ability to freely examine and modify source code and
exemption from software licensing fees.  However, since open source
software is typically developed by a large number of volunteer
programmers, the resulting code is often not as clearly organized and
its user interface not as standardized as in a mature commercial
product.  In addition, in any project under active development,
documentation may not keep up with the development of new features.
Consequently the learning curve for actively developed, open source
source software is sometimes steep.

This tutorial is intended to ease the learning curve for new users of
bioperl.  To that end the tutorial includes:

=over 4

=item *

Descriptions of what bioinformatics tasks can be handled with bioperl

=item *

Directions on where to find the methods to accomplish these tasks
within the bioperl package

=item *

Recommendations on where to go for additional information.

=item *

A runnable script, bptutorial.pl, which demonstrates many of the
capabilities of Bioperl. Runnable example code can also be found in
the scripts/ and examples/ directories. Summary descriptions of all
of these scripts can be found in the file bioscripts.pod (or
http://bioperl.org/Core/Latest/bioscripts.html).  In addition, the POD 
documentation for many Bioperl modules should contain
runnable code in the SYNOPSIS section which is meant to illustrate the
use of a module and its methods. You will also find some interesting
bits of code in the FAQ (http://bioperl.org/Core/Latest/faq.html).

=back

Running the bptutorial.pl script while going through this tutorial - or
better yet, stepping through it with an interactive debugger - is a
good way of learning bioperl.  The tutorial script is also a good
place from which to cut-and-paste code for your scripts (rather than
using the code snippets in this tutorial). Most of the scripts in the
tutorial script should work on your machine - and if they don't it would
probably be a good idea to find out why, before getting too involved
with bioperl! Some of the demos require optional modules from the
bioperl auxiliary libraries and/or external programs.  These demos
should be skipped if the demos are run and the required auxiliary
programs are not found.

=head2 I.2 Quick getting started scripts

For newcomers and people who want to quickly evaluate whether this package
is worth using in the first place, we have a very simple module which allows
easy access to a small number of Bioperl's functionality in an easy to use 
manner. The Bio::Perl module provides some simple access functions,
for example, this script will retrieve a swissprot sequence and write
it out in fasta format

  use Bio::Perl;

  # this script will only work with an internet connection
  # on the computer it is run on
  $seq_object = get_sequence('swissprot',"ROA1_HUMAN");

  write_sequence(">roa1.fasta",'fasta',$seq_object);

Another example is the ability to blast a sequence using the facilities
as NCBI. Please be careful not to abuse the compute that NCBI provides
and so use this only for individual searches. If you want to do a large
number of BLAST searches, please download the blast package locally.

  use Bio::Perl;

  # this script will only work with an internet connection
  # on the computer it is run on

  $seq = get_sequence('swissprot',"ROA1_HUMAN");

  # uses the default database - nr in this case
  $blast_result = blast_sequence($seq);

  write_blast(">roa1.blast",$blast_result);

Bio::Perl has a number of other easy-to-use functions, including

  get_sequence        - gets a sequence from standard, internet accessible
                        databases
  read_sequence       - reads a sequence from a file
  read_all_sequences  - reads all sequences from a file 
  new_sequence        - makes a bioperl sequence just from a string
  write_sequence      - writes a single or an array of sequence to a file
  translate           - provides a translation of a sequence
  translate_as_string - provides a translation of a sequence, returning back 
                        just the sequence as a string
  blast_sequence      - BLASTs a sequence against standard databases at  
                        NCBI
  write_blast         - writes a blast report out to a file

Using the Bio::Perl.pm module, it is possible to manipulate sequence
data in Bioperl without explicitly creating Seq or SeqIO objects 
described later in this tutorial. However, only limited
data manipulation is supported in this mode.

Look at the documentation in L<Bio::Perl> by going 'perldoc Bio::Perl' to
learn more about these functions. In all these cases, Bio::Perl
accesses a subset of the underlying Bioperl functions (for example,
translation in Bioperl can handle many different translation tables
and provides different options for stop codon processing) - in most
cases, most users will migrate to using the underlying bioperl objects
as their sophistication level increases, but Bio::Perl provides an
easy on-ramp for newcomers and lazy programmers. Also see examples/bioperl.pl
for more examples of usage of this module.

=head2 I.3 Software requirements

What's required to run bioperl.

=head2 I.3.1 Minimal bioperl installation (Bioperl "core" installation)

For a minimal installation of bioperl, you will need to have perl
itself installed as well as the bioperl "core modules".  Bioperl has
been tested primarily using perl 5.005, 5.6, and 5.8.
The minimal bioperl installation should still work under perl 5.004.
However, as increasing numbers of bioperl objects are using modules
from CPAN (see below), problems have been observed for bioperl running
under perl 5.004.  So if you are having trouble running bioperl under
perl 5.004, you should probably upgrade your version of perl.

In addition to a current version of perl, the new user of bioperl is
encouraged to have access to, and familiarity with, an interactive
perl debugger.  Bioperl is a large collection of complex interacting
software objects.  Stepping through a script with an interactive
debugger is a very helpful way of seeing what is happening in such a
complex software system - especially when the software is not behaving
in the way that you expect.  The free graphical debugger ptkdb
is highly recommended - it's available as Devel::ptkdb from CPAN.
The standard perl distribution also contains a powerful interactive
debugger with a command-line interface (use it like "perl -d <script>").

The Perl tool Data::Dumper used with the syntax:

  use Data::Dumper;
  print Dumper($seqobj);

can also be helpful for obtaining debugging information on Bioperl objects.

=head2 I.3.2 Complete installation

Some of the capabilities of bioperl require software beyond that of
the minimal installation.  This additional software includes perl
modules from CPAN, package-libraries from bioperl's auxiliary
code-repositories, a bioperl xs-extension, and several standard
compiled bioinformatics programs.

B<Perl - extensions>

For a complete listing of external Perl modules required by bioperl
please see the INSTALL file in the Bioperl package.

B<Bioperl auxiliary repositories>

Some features of bioperl that require modules from bioperl's
auxiliary code repositories. See section IV and references therein
for further installation instructions for these modules.

B<Bioperl C extensions & external bioinformatics programs>

Bioperl also uses several C programs for sequence alignment and local
blast searching. To use these features of bioperl you will need an
ANSI C or Gnu C compiler as well as the actual program available from
sources such as:

for Smith-Waterman alignments- bioperl-ext-0.6 from
http://bioperl.org/Core/external.shtml

for clustalw alignments-
ftp://ftp.ebi.ac.uk/pub/software/unix/clustalw/
ftp://ftp-igbmc.u-strasbg.fr/pub/ClustalW/

for tcoffee alignments-
http://igs-server.cnrs-mrs.fr/~cnotred/Projects_home_page/t_coffee_home_page.html

for local blast searching- ftp://ftp.ncbi.nih.gov/blast/executables/release/

for EMBOSS applications - http://www.emboss.org

=for html <A NAME ="i.3"></A>

=head2  I.4 Installation

The actual installation of the various system components is
accomplished in the standard manner:

=over 6

=item *

Locate the package on the network

=item *

Download

=item *

Decompress (with gunzip or a similiar utility)

=item *

Extract the file archive (e.g. with tar -xvf)

=item *

Create a Makefile with "perl Makefile.PL"

=item *

Run "make", "make test" and "make install". This procedure must be
repeated for every CPAN module, bioperl-extension and external
module to be installed. A helper module CPAN.pm is available from
CPAN which automates the process for installing the perl modules.

The CPAN module can also be used to install all of the modules
listed above in a single step as a "bundle" of modules,
Bundle::BioPerl, eg

  $>perl -MCPAN -e shell
  cpan>install Bundle::BioPerl
  <installation details....>
  cpan>install B/BI/BIRNEY/bioperl-1.2.2.tar.gz
  <installation details....>
  cpan>quit

Be advised that version numbers change regularly, so the number used
above may not apply. A disadvantage of the "bundle" approach is that
if there's a problem installing any individual module it may be a bit
more difficult to isolate.

See bioperl's INSTALL file for more details.

=back

For the external programs (clustal, Tcoffee, ncbi-blast), there is an
extra step:

=over 1

=item *

Set the relevant environmental variable (CLUSTALDIR, TCOFFEEDIR or
BLASTDIR) to the directory holding the executable in your startup
file - e.g. in .bashrc or .tcshrc. For running local blasts, it is also
necessary that the name of local-blast database directory is known
to bioperl.  This will typically happen automatically, but in case
of difficulty, refer to the documentation in
L<Bio::Tools::Run::StandAloneBlast>.

=back

The only likely complication (at least on unix systems) that may occur
is if you are unable to obtain system level writing privileges.  For
instructions on modifying the installation in this case and for more
details on the overall installation procedure, see the INSTALL file in
the bioperl distribution as well as the README files in the external
programs you want to use (e.g. bioperl-ext, clustalw, TCoffee,
NCBI-blast).

=head2 I.5 Additional comments for non-unix users

Bioperl has mainly been developed and tested under various unix
environments, including Linux and MacOS X.  In addition, this tutorial
has been written largely from a Unix perspective.

Mac users may find Steve Cannon's installation notes and suggestions
for Bioperl on OS X at
http://www.tc.umn.edu/~cann0010/Bioperl_OSX_install.html helpful. Also
Todd Richmond has written of his experiences with BioPerl on MacOS 9
(http://bioperl.org/Core/mac-bioperl.html).

The bioperl core has also been tested and should work under most
versions of Microsoft Windows.  For many windows users the perl and
bioperl distributions from Active State, at http://www.activestate.com
has been quite helpful.  Other windows users have had success running
bioperl under Cygwin (http://www.cygwin.com). See the package's
INSTALL.WIN file for more details.

Many bioperl features require the use of CPAN modules, compiled
extensions or external programs.  These features probably will
not work under some or all of these other operating systems.  If a
script attempts to access these features from a non-unix OS, bioperl
is designed to simply report that the desired capability is not
available.  However, since the testing of bioperl in these
environments has been limited, the script may well crash in a less
graceful manner.

=head2 I.6 Places to look for additional documentation

This tutorial does not intend to be a comprehensive description of all
the objects and methods available in bioperl.  For that the reader is
directed to the documentation included with each of the modules. A
very useful interface for finding one's way within all the module
documentation can be found at http://doc.bioperl.org/bioperl-live/.
This interface lists all bioperl modules and descriptions of all
of their methods. In addition, beginner questions can often be
answered by looking at the FAQ, INSTALL and README files 
(http://bioperl.org/Core/Latest/faq.html,
http://bioperl.org/Core/Latest/INSTALL,
http://bioperl.org/Core/Latest/README )in the top-level directory of 
the bioperl distribution.

One potential problem in locating the correct documentation is that
multiple methods in different modules may all share the same name.
Moreover, because of perl's complex method of inheritance
it is not often clear which of the identically named methods is being
called by a given object. One way to resolve this question is by using
the software described in Appendix L<"V.1">.

For those who prefer more visual descriptions,
http://bioperl.org/Core/Latest/modules.html also offers links to
PDF files which contain class diagrams that describe how many of the 
bioperl objects related to one another (Version 1.0 Class Diagrams).

In addition, a bioperl online course is available on the web at
http://www.pasteur.fr/recherche/unites/sis/formation/bioperl. The
user is also referred to numerous bioperl scripts in the scripts/
and examples/ directories (see bioscripts.pod for a description of 
these scripts, or http://bioperl.org/Core/Latest/bioscripts.html).

Another source of focussed documentation is the HOWTO files, found
either in the bioperl doc/howto directory or at http://bioperl.org/HOWTOs/.
Current topics include OBDA Access, SeqIO, SearchIO, and BioGraphics.


=head1 II. Brief introduction to bioperl's objects

The purpose of this tutorial is to get you using bioperl to solve
real-life bioinformatics problems as quickly as possible.  The aim is
not to explain the structure of bioperl objects or perl
object-oriented programming in general.  Indeed, the relationships
among the bioperl objects is not simple; however, understanding them
in detail is fortunately not necessary for successfully using the
package.

Nevertheless, a little familiarity with the bioperl object bestiary
can be very helpful even to the casual user of bioperl. For example
there are (at least) eight different "sequence objects" - Seq,
PrimarySeq, LocatableSeq, RelSegment, LiveSeq, LargeSeq, SeqI, and
SeqWithQuality.  Understanding the relationships among these objects -
and why there are so many of them - will help you select the
appropriate one to use in your script.

=for html <A NAME ="ii.1"></A>

=head2 II.1 Sequence objects (Seq, PrimarySeq, LocatableSeq, RelSegment, LiveSeq, LargeSeq, RichSeq, SeqWithQuality, SeqI)

This section describes various Bioperl sequence objects. Many people 
using Bioperl will never know, or need to know, what kind of sequence 
object they are using. This is because the SeqIO module, section
section L<"III.2.1">, creates exactly the right type of object when 
given a file or a filehandle or a string. But if you're curious, or if
you need to create a sequence object manually for some reason, then
read on.

Seq is the central sequence object in bioperl.  When in doubt this is
probably the object that you want to use to describe a DNA, RNA or
protein sequence in bioperl.  Most common sequence manipulations can
be performed with Seq.  These capabilities are described in sections
L<"III.3.1"> and L<"III.7.1">, or in L<Bio::Seq>.

Seq objects may be created for you
automatically when you read in a file containing sequence data using
the SeqIO object.  This procedure is described in section L<"III.2.1">.
In addition to storing its identification labels and the sequence itself,
a Seq object can store multiple annotations and associated "sequence
features", such as those contained in most Genbank and EMBL sequence files.
This capability can be very useful - especially in development of
automated genome annotation systems, see section L<"III.7.1">.

On the other hand, if you need a script capable of simultaneously
handling hundreds or thousands sequences at a time, then the
overhead of adding annotations to each sequence can be significant.
For such applications, you will want to use the PrimarySeq
object. PrimarySeq is basically a stripped-down version of Seq.
It contains just the sequence data itself and a few identifying labels
(id, accession number, alphabet = dna, rna, or protein), and no features.
For applications with hundreds or thousands or sequences, using PrimarySeq
objects can significantly speed up program execution and decrease the
amount of RAM the program requires. See L<Bio::PrimarySeq> for more
details.

RichSeq objects store additional annotations beyond those used by
standard Seq objects.  If you are using sources with very rich
sequence annotation, you may want to consider using these objects
which are described in section L<"III.7.1">. RichSeq objects are
created automatically when Genbank, EMBL, or Swissprot format files
are read by SeqIO.

SeqWithQuality objects areu sed to manipulate sequences with quality data, 
like those produced by phred.  These objects are described in section L<"III.7.6">,
L<Bio::Seq::RichSeqI>, and in L<Bio::Seq::SeqWithQuality>.

What is called a LocatableSeq object for historical reasons
might be more appropriately called an "AlignedSeq" object.  It is a Seq
object which is part of a multiple sequence alignment.  It has start and
end positions indicating from where in a larger sequence it may have
been extracted.  It also may have gap symbols corresponding to the
alignment to which it belongs.  It is used by the alignment
object SimpleAlign and other modules that use SimpleAlign objects
(e.g. AlignIO.pm, pSW.pm).

In general you don't have to worry about creating LocatableSeq objects 
because they will be made for you automatically when you create an 
alignment (using pSW, Clustalw, Tcoffee, Lagan, or bl2seq) or when you 
input an alignment data file using AlignIO. However if you need to 
input a sequence alignment by hand (e.g. to build a SimpleAlign object), 
you will need to input the sequences as LocatableSeqs. Other sources of 
information include L<Bio::LocatableSeq>, L<Bio::SimpleAlign>, 
L<Bio::AlignIO>, and L<Bio::Tools::pSW>.

The RelSegment object is also a type of bioperl Seq object. RelSegment
objects are useful when you want to be able to manipulate the origin
of the genomic coordinate system.  This situation may occur when
looking at a sub-sequence (e.g. an exon) which is located on a longer
underlying underlying sequence such as a chromosome or a contig. Such
manipulations may be important, for example when designing a graphical
genome browser. If your code may need such a capability, look at the
documentation L<Bio::DB::GFF::RelSegment> which describes this feature
in detail.

A LargeSeq object is a special type of Seq object used for
handling very long sequences (e.g. E<gt> 100 MB).  If you need to
manipulate such long sequences see section L<"III.7.3"> which describes
LargeSeq objects, or L<Bio::Seq::LargeSeq>.

A LiveSeq object is another specialized object for storing
sequence data. LiveSeq addresses the problem of features whose location
on a sequence changes over time.  This can happen, for example, when
sequence feature objects are used to store gene locations on newly
sequenced genomes - locations which can change as higher quality
sequencing data becomes available.  Although a LiveSeq object is not
implemented in the same way as a Seq object, LiveSeq does implement
the SeqI interface (see below). Consequently, most methods available
for Seq objects will work fine with LiveSeq objects. Section L<"III.7.4">
and L<Bio::LiveSeq> contain further discussion of LiveSeq objects.

SeqI objects are Seq "interface objects" (see section L<"II.4"> and
L<Bio::SeqI>). They are used to ensure bioperl's compatibility with
other software packages. SeqI and other interface objects are not
likely to be relevant to the casual bioperl user.

=for html <A NAME ="ii.2"></A>

=head2 II.2 Location objects

A Location object is designed to be associated with a Sequence
Feature object in order to show where the feature is on a longer sequence.
Location objects can also be standalone objects used to described 
positions. The reason why these simple concepts have evolved into a 
collection of rather complicated objects is that:

1) Some objects have multiple locations or sub-locations (e.g. a gene's exons
may have multiple start and stop locations)
2) In unfinished genomes, the precise locations of features is not known with
certainty.

Bioperl's various Location objects address these complications. In addition
there are CoordinatePolicy objects that allow the user to specify how to
measure the length of a feature if its precise start and end coordinates are
not known. In most cases, you will not need to worry about these complications
if you are using bioperl to handle simple features with well-defined start
and stop locations.  However, if you are using bioperl to annotate partially
or unfinished genomes or to read annotations of such genomes with bioperl,
understanding the various Location objects will be important.  See the
documentation of the various modules in the Bio::Locations directory or
L<Bio::Location::CoordinatePolicyI> or section L<"III.7.1"> for more 
information.

=for html <A NAME ="ii.4"></A>

=head2 II.4 Interface objects and implementation objects

One goal of the design of Bioperl is to separate interface and
implementation objects.  An interface is solely the definition of what
methods one can call on an object, without any knowledge of how it is
implemented. An implementation is an actual, working implementation of
an object. In languages like Java, interface definition is part of the
language. In Perl, you have to roll your own.

In bioperl, the interface objects usually have names like
Bio::MyObjectI, with the trailing I indicating it is an interface
object. The interface objects mainly provide documentation on what the
interface is, and how to use it, without any implementations (though
there are some exceptions).  Although interface objects are not of
much direct utility to the casual bioperl user, being aware of their
existence is useful since they are the basis to understanding how
bioperl programs can communicate with other bioinformatics projects
and computer languages such as Ensembl and biopython and biojava.

For more discussion of design and development issues please see the
biodesign.pod file in the package or biodesign.html
(http://bioperl.org/Core/Latest/biodesign.html).


=head1 III. Using bioperl

Bioperl provides software modules for many of the typical tasks of
bioinformatics programming.  These include:

=over 7

=item * Accessing sequence data from local and remote databases

=item * Transforming formats of database/ file records

=item * Manipulating individual sequences

=item * Searching for similar sequences

=item * Creating and manipulating sequence alignments

=item * Searching for genes and other structures on genomic DNA

=item * Developing machine readable sequence annotations

=back

The following sections describe how bioperl can help perform all of
these tasks.

=head2 III.1 Accessing sequence data from local and remote databases

Much of bioperl is focused on sequence manipulation.  However, before
bioperl can manipulate sequences, it needs to have access to sequence
data.  Now one can directly enter data sequence data into a bioperl
Seq object, eg:

  $seq = Bio::Seq->new(-seq              => 'actgtggcgtcaact',
                       -desc             => 'Sample Bio::Seq object',
                       -display_id       => 'something',
                       -accession_number => 'accnum',
                       -alphabet         => 'dna' );

However, in most cases, it is preferable to access sequence data from
some online data file or database. Note that in common with
conventional bioinformatics usage we will sometimes call a "database"
what might be more appropriately referred to as an "indexed flat
file".

Bioperl supports accessing remote databases as well as creating 
indices for accessing local databases.  There are two general approaches 
to accomplishing this.  If you know what kind of database the sequences 
are stored in (i.e. flat file, local relational database or a database 
accessed remotely over the internet), you can write a script that specifically 
accesses data from that kind of database.  This approach is described 
in sections III.1.1 and III.1.2 for access from remote databases and 
local indexed flat files respectively. To explicitly access sequence 
data from a local relational database requires installing and setting 
up the modules in the bioperl-db library and the BioSQL schema, see
L<"IV.3"> for more information.

The other approach is to use the recently developed OBDA (Open
Bioinformatics Data Access) Registry system.  Using OBDA it is
possible to import sequence data from a database without your needing
to know whether the required database is flat-file or relational or
even whether it is local or accessible only over the net.
Descriptions of how to set up the necessary registry configuration
file and access sequence data with the registry in described in
BIODATABASE_ACCESS in the doc/howto subdirectory and won't be repeated
here.

=head2   III.1.1 Accessing remote databases (Bio::DB::GenBank, etc)

Accessing sequence data from the principal molecular biology databases
is straightforward in bioperl.  Data can be accessed by means of the
sequence's accession number or id.  Batch mode access is also
supported to facilitate the efficient retrieval of multiple sequences.
For retrieving data from genbank, for example, the code could be as
follows:

  $gb = new Bio::DB::GenBank();
  # this returns a Seq object :
  $seq1 = $gb->get_Seq_by_id('MUSIGHBA1');
  # this returns a Seq object :
  $seq2 = $gb->get_Seq_by_acc('AF303112');
  # this returns a SeqIO object :
  $seqio = $gb->get_Stream_by_id(["J00522","AF303112","2981014"]);

See section L<"III.2.1"> for information on using this SeqIO object.

Bioperl currently supports sequence data retrieval from the genbank,
genpept, RefSeq, swissprot, and EMBL databases. See L<Bio::DB::GenBank>,
L<Bio::DB::GenPept>, L<Bio::DB::SwissProt>, L<Bio::DB::RefSeq> and
L<Bio::DB::EMBL> for more information. A user can also specify a different
database mirror for a database - this is especially relevent for the SwissProt
resource where there are many ExPaSy mirrors.  There are also configuration
options for specifying local proxy servers for those behind firewalls.

The retrieval of NCBI RefSeqs sequences is supported through a special
module called Bio::DB::RefSeq which actually queries an EBI server.
Please see L<Bio::DB::RefSeq> before using it as there are some caveats
with RefSeq retrieval. RefSeq ids in Genbank begin with "NT_", "NC_",
"NG_", "NM_", "NP_", "XM_", "XR_", or "XP_" (for more information see
http://www.ncbi.nlm.nih.gov/LocusLink/refseq.html). Bio::DB::GenBank
can be used to retrieve entries corresponding to these ids but bear in
mind that these are not Genbank entries, strictly speaking. See
L<Bio::DB::GenBank> for special details on retrieving entries beginning
with "NT_", these are specially formatted "CONTIG" entries.

Bioperl also supports retrieval from a remote Ace database. This
capability requires the presence of the external AcePerl module. You
need to download and install the aceperl module from
http://stein.cshl.org/AcePerl/.

An additional module is available for accessing remote databases, BioFetch,
which queries the dbfetch script at EBI. The available databases are EMBL,
GenBank, or SWALL, and the entries can be retrieved in different formats 
as objects or streams (SeqIO objects), or as "tempfiles". See
L<Bio::DB::BioFetch> for the details.


=head2  III.1.2 Indexing and accessing local databases (Bio::Index::*, bp_index.pl, bp_fetch.pl, Bio::DB::*)

Alternately, bioperl permits indexing local sequence data files by
means of the Bio::Index or Bio::DB::Fasta objects.  The following sequence
data formats are supported by Bio::Index: genbank, swissprot, pfam, embl and
fasta.  Once the set of sequences have been indexed using Bio::Index,
individual sequences can be accessed using syntax very similar to that
described above for accessing remote databases.  For example, if one wants to
set up an indexed flat-file database of fasta files, and later wants then to
retrieve one file, one could write scripts like:

  # script 1: create the index
  use Bio::Index::Fasta; # using fasta file format
  use strict; # some users have reported that this is necessary

  my $Index_File_Name = shift;
  my $inx = Bio::Index::Fasta->new(
      -filename => $Index_File_Name,
      -write_flag => 1);
  $inx->make_index(@ARGV);

  # script 2: retrieve some files
  use Bio::Index::Fasta;
  use strict; # some users have reported that this is necessary

  my $Index_File_Name = shift;
  my $inx = Bio::Index::Fasta->new($Index_File_Name);
  foreach  my $id (@ARGV) {
      my $seq = $inx->fetch($id);  # Returns Bio::Seq object
      # do something with the sequence
  }

To facilitate the creation and use of more complex or flexible
indexing systems, the bioperl distribution includes two sample scripts
in the scripts/index directory, bp_index.PLS and bp_fetch.PLS.  These scripts
can be used as templates to develop customized local data-file indexing
systems.

Bioperl also supplies Bio::DB::Fasta as a means to index and query Fasta
format files. It's similar in spirit to Bio::Index::Fasta but offers more
methods, e.g.

  use Bio::DB::Fasta;
  use strict;

  my $db = Bio::DB::Fasta->new($file);  # one file or many files
  my $seqstring = $db->seq($id);        # get a sequence as string
  my $seqobj = $db->get_Seq_by_id($id); # get a PrimarySeq obj
  my $desc = $db->header($id);          # get the header, or description line

See L<Bio::DB::Fasta> for more information on this fully-featured module.

Both modules also offer the user the ability to designate a specific string
within the fasta header as the desired id, such as the gi number within the
string "gi|4556644|gb|X45555". Consider the following fasta-formatted 
sequence, in "test.fa":

  >gi|523232|emb|AAC12345|sp|D12567 titin fragment
  MHRHHRTGYSAAYGPLKJHGYVHFIMCVVVSWWASDVVTYIPLLLNNSSAGWKRWWWIIFGGE
  GHGHHRTYSALWWPPLKJHGSKHFILCVKVSWLAKKERTYIPKKILLMMGGWWAAWWWI

By default Bio::Index::Fasta and Bio::DB::Fasta will use the first "word" 
they encounter in the fasta header as the retrieval key, in this case 
"gi|523232|emb|AAC12345|sp|D12567". What would be more useful as a key 
would be a single id.  The code below will index the "test.fa" file and 
create an index file called "test.fa.idx" where the keys are the Swissprot,
or "sp", identifiers.

  $ENV{BIOPERL_INDEX_TYPE} = "SDBM_File";
  # look for the index in the current directory
  $ENV{BIOPERL_INDEX} = ".";

  my $file_name = "test.fa";
  my $inx = Bio::Index::Fasta->new( -filename   => $file_name . ".idx",
     				    -write_flag => 1 );
  # pass a reference to the critical function to the Bio::Index object
  $inx->id_parser(\&get_id);
  # make the index
  $inx->make_index($file_name);

  # here is where the retrieval key is specified
  sub get_id {
     my $header = shift;
     $header =~ /^>.*\bsp\|([A-Z]\d{5}\b)/;
     $1;
  }

Here is how you would retrieve the sequence, as a Bio::Seq object:

  my $seq = $inx->fetch("D12567");
  print $seq->seq;

What if you wanted to retrieve a sequence using either a Swissprot id
or a gi number and the fasta header was actually a concatenation of headers
with multiple gi's and Swissprots?

  >gi|523232|emb|AAC12345|sp|D12567|gi|7744242|sp|V11223 titin fragment

Modify the function that's passed to the id_parser method:

  sub get_id {
     my $header = shift;
     my (@sps) = $header =~ /^>.*\bsp\|([A-Z]\d{5})\b/g;
     my (@gis) = $header =~ /gi\|(\d+)\b/g;
     return (@sps,@gis);
  }

The Bio::DB::Fasta module uses the same principle, but the syntax is 
slightly different, for example:

  my $db = Bio::DB::Fasta->new('test.fa', -makeid=>\&make_my_id);
  my $seqobj = $db->get_Seq_by_id($id);

  sub make_my_id {
     my $description_line = shift;
     $description_line =~ /gi\|(\d+)\|emb\|(\w+)/;
     ($1,$2);
  }

The core bioperl installation does not support accessing sequences
and data stored in relational databases. However, this capability is
available with the auxiliary bioperl-db library. See section L<"IV.3"> for
more information.

=head2 III.2 Transforming formats of database/ file records

=for html <A NAME ="iii.2.1"></A>

=head2   III.2.1 Transforming sequence files (SeqIO)

A common - and tedious - bioinformatics task is that of converting
sequence data among the many widely used data formats.  Bioperl's
SeqIO object, however, makes this chore a breeze.  SeqIO can
read a stream of sequences - located in a single or in multiple files -
in a number of formats: Fasta, EMBL, GenBank, Swissprot, PIR, GCG, SCF,
phd/phred, Ace, fastq, exp, chado, or raw (plain sequence). SeqIO can 
also parse tracefiles in alf, ztr, abi, ctf, and ctr format Once the 
sequence data has been read in with SeqIO, it is available to bioperl 
in the form of Seq, PrimarySeq, or RichSeq objects, depending on what
the sequence source is.  Moreover, the sequence objects can then be 
written to another file (again using SeqIO) in any of the supported 
data formats making data converters simple to implement, for example:

  use Bio::SeqIO;
  $in  = Bio::SeqIO->new(-file => "inputfilename",
                         -format => 'Fasta');
  $out = Bio::SeqIO->new(-file => ">outputfilename",
                         -format => 'EMBL');
  while ( my $seq = $in->next_seq() ) {$out->write_seq($seq); }

In addition, the perl "tied filehandle" syntax is available to SeqIO,
allowing you to use the standard E<lt>E<gt> and print operations to read
and write sequence objects, eg:

  $in  = Bio::SeqIO->newFh(-file => "inputfilename" ,
                           -format => 'fasta');
  $out = Bio::SeqIO->newFh(-format => 'embl');
  print $out $_ while <$in>;

If the "-format" argument isn't used then Bioperl will try to determine 
the format based on the file's suffix, in a case-insensitive manner. If 
there's no suffix available then SeqIO will attempt to guess the format 
based on actual content. Here is the current set of suffixes:

   Format     Suffixes                     Comment

   fasta      fasta|fast|seq|fa|fsa|nt|aa  Fasta
   genbank    gb|gbank|genbank|gbs|gbk     Genbank
   scf        scf                          SCF tracefile
   pir        pir                          PIR
   embl       embl|ebl|emb|dat             EMBL
   raw        txt                          plain
   gcg        gcg                          GCG
   ace        ace                          ACeDB
   bsml       bsm|bsml                     BSML XML
   game                                    GAME XML
   swiss      swiss|sp                     SwissProt
   phd        phd|phred                    Phred
   fastq      fastq                        Fastq
   Locuslink                               LL_tmpl format
   qual                                    Phred quality file
   chado                                   Chado XML
   exp        exp                          Staden experiment file
   abi*       abi                          ABI tracefile
   alf*       alf                          ALF tracefile
   ctf*       ctf                          CTF tracefile
   ztr*       ztr                          ZTR tracefile
   pln*       pln                          Staden plain tracefile

* These formats require the bioperl-ext package and the io_lib library
  from the Staden package

For more information see L<Bio::SeqIO> or the SeqIO HOWTO
(http://bioperl.org/HOWTOs/html/SeqIO.html).

=for html <A NAME ="iii.2.2"></A>

=head2 III.2.2 Transforming alignment files (AlignIO)

Data files storing multiple sequence alignments also appear in varied
formats.  AlignIO is the bioperl object for conversion of
alignment files. AlignIO is patterned on the SeqIO object and its commands
have many of the same names as the commands in SeqIO. Just as in SeqIO the
AlignIO object can be created with "-file" and "-format" options:

  use Bio::AlignIO;
  my $io = Bio::AlignIO->new(-file   => "receptors.aln",
                             -format => "clustalw" );

If the "-format" argument isn't used then Bioperl will try and determine the 
format based on the file's suffix, in a case-insensitive manner.  Here is the 
current set of suffixes:

   Format      Suffixes                     Comment

   bl2seq
   clustalw    aln
   emboss*     water|needle
   fasta       fasta|fast|seq|fa|fsa|nt|aa
   mase                                     Seaview
   mega        meg|mega
   meme        meme
   metafasta
   msf         msf|pileup|gcg               GCG
   nexus       nexus|nex
   pfam        pfam|pfm
   phylip      phylip|phlp|phyl|phy|phy|ph  interleaved
   prodom
   psi         psi                          PSI-BLAST
   selex       selex|slx|selx|slex|sx       HMMER
   stockholm

*water, needle, matcher, stretcher, merger, and supermatcher
See L<"IV.2.1"> on EMBOSS for more information

Unlike SeqIO AlignIO cannot create output files in every format. AlignIO
currently supports output in these 6 formats: fasta, mase, selex, clustalw,
msf/gcg, and phylip (interleaved).

Another significant difference between AlignIO and SeqIO is that AlignIO 
handles IO for only a single alignment at a time but SeqIO.pm handles IO 
for multiple sequences in a single stream. Syntax for AlignIO is almost 
identical to that of SeqIO:

  use Bio::AlignIO;
  $in  = Bio::AlignIO->new(-file => "inputfilename" ,
                           -format => 'fasta');
  $out = Bio::AlignIO->new(-file => ">outputfilename",
                           -format => 'pfam');
  while ( my $aln = $in->next_aln() ) { $out->write_aln($aln); }

The only difference is that the returned object reference, $aln,
is to a SimpleAlign object rather than to a Seq object.

AlignIO also supports the tied filehandle syntax described above for
SeqIO.  See L<Bio::AlignIO>, L<Bio::SimpleAlign>, and section L<"III.5"> 
on SimpleAlign for more information.

=head2 III.3 Manipulating sequences

Bioperl contains many modules with functions for sequence analysis. And
if you cannot find the function you want in bioperl you may be able to
find it in EMBOSS or PISE , which are accessible through the bioperl-run
auxiliary library (see L<"IV.2.1">).

=for html <A NAME ="iii.3.1"></A>

=head2 III.3.1  Manipulating sequence data with Seq methods

OK, so we know how to retrieve sequences and access them as sequence
objects.  Let's see how we can use sequence objects to manipulate our
sequence data and retrieve information.  Seq provides multiple
methods for performing many common (and some not-so-common) tasks of
sequence manipulation and data retrieval.  Here are some of the most
useful:

These methods return strings or may be used to set values:

  $seqobj->display_id();       # the human read-able id of the sequence
  $seqobj->seq();              # string of sequence
  $seqobj->subseq(5,10);       # part of the sequence as a string
  $seqobj->accession_number(); # when there, the accession number
  $seqobj->alphabet();         # one of 'dna','rna','protein'
  $seqobj->primary_id();       # a unique id for this sequence irregardless
                               # of its display_id or accession number
  $seqobj->desc();             # a description of the sequence

It is worth mentioning that some of these values correspond to specific
fields of given formats. For example, the display_id method returns
the LOCUS name of a Genbank entry, the (\S+) following the E<gt> character
in a Fasta file, the ID from a SwissProt file, and so on. The desc()
method will return the DEFINITION line of a Genbank file, the line
following the display_id in a Fasta file, and the DE field in a SwissProt
file.

The following methods return an array of Bio::SeqFeature objects:

   $seqobj->get_SeqFeatures;      # The 'top level' sequence features
   $seqobj->get_all_SeqFeatures;  # All sequence features, including sub-
                                  # seq features

For a comment annotation, you can use:

   use Bio::Annotation::Comment;
   $seq->annotation->add_Annotation('comment',
      Bio::Annotation::Comment->new(-text => 'some description');

For a reference annotation, you can use:

   use Bio::Annotation::Reference;
   $seq->annotation->add_Annotation('reference',
      Bio::Annotation::Reference->new(-authors  => 'author1,author2',
                                      -title    => 'title line',
                                      -location => 'location line',
                                      -medline  => 998122 );

Sequence features will be discussed further in section L<"III.7"> on
machine-readable sequence annotation. A general description of the
object can be found in L<Bio::SeqFeature::Generic>, and a description
of related, top-level annotation is found in L<Bio::Annotation::Collection>.

Additional sample code for obtaining sequence features can be found in
the script gb2features.pl in the subdirectory examples/DB. Finally,
there's a HOWTO on features and annotations
(http://bioperl.org/HOWTOs/html/Feature-Annotation.html) and there's a 
section on features in the FAQ (http://bioperl.org/Core/Latest/faq.html#5).

The following methods returns new sequence objects, but do not transfer
the features from the starting object to the resulting feature:

  $seqobj->trunc(5,10);  # truncation from 5 to 10 as new object
  $seqobj->revcom;       # reverse complements sequence
  $seqobj->translate;    # translation of the sequence

Note that some methods return strings, some return arrays and some
return objects. See L<Bio::Seq> for more information.

Many of these methods are self-explanatory. However, bioperl's flexible
translation methods warrant further comment. Translation in bioinformatics
can mean two slightly different things:

=over 2

=item 1 Translating a nucleotide sequence from start to end.

=item 2 Taking into account the constraints of real coding regions in mRNAs.

=back

The bioperl implementation of sequence-translation does the first of
these tasks easily. Any sequence object which is not of alphabet 'protein'
can be translated by simply calling the method which returns a protein
sequence object:

  $translation1 = $my_seq_object->translate;

However, the translate method can also be passed several optional
parameters to modify its behavior. For example, the first two
arguments to translate() can be used to modify the characters used to
represent stop (default '*') and unknown amino acid ('X'). (These are
normally best left untouched.)  The third argument determines the
frame of the translation. The default frame is "0".  To get
translations in the other two forward frames, we would write:

  $translation2 = $my_seq_object->translate(undef,undef,1);
  $translation3 = $my_seq_object->translate(undef,undef,2);

The fourth argument to translate() makes it possible to use
alternative genetic codes. There are currently 16 codon tables
defined, including tables for 'Vertebrate Mitochondrial', 'Bacterial',
'Alternative Yeast Nuclear' and 'Ciliate, Dasycladacean and Hexamita
Nuclear' translation. These tables are located in the object
Bio::Tools::CodonTable which is used by the translate method. For
example, for mitochondrial translation:

  $human_mitochondrial_translation = $seq_obj->translate(undef,undef,undef,2);

If we want to translate full coding regions (CDS) the way major
nucleotide databanks EMBL, GenBank and DDBJ do it, the translate
method has to perform more tricks. Specifically, 'translate' needs to
confirm that the sequence has appropriate start and terminator codons
at the beginning and the end of the sequence and that there are no
terminator codons present within the sequence.  In addition, if the
genetic code being used has an atypical (non-ATG) start codon, the
translate method needs to convert the initial amino acid to
methionine.  These checks and conversions are triggered by setting the
fifth argument of the translate method to evaluate to "true".

If argument 5 is set to true and the criteria for a proper CDS are
not met, the method, by default, issues a warning. By setting the
sixth argument to evaluate to "true", one can instead instruct
the program to die if an improper CDS is found, e.g.

  $protein_object = $cds->translate(undef,undef,undef,undef,1,'die_if_errors');

See L<Bio::Tools::CodonTable> for related details.

=head2 III.3.2 Obtaining basic sequence statistics (SeqStats,SeqWord)

In addition to the methods directly available in the Seq object,
bioperl provides various helper objects to determine additional
information about a sequence.  For example, SeqStats object provides
methods for obtaining the molecular weight of the sequence as well the
number of occurrences of each of the component residues (bases for a
nucleic acid or amino acids for a protein.)  For nucleic acids,
SeqStats also returns counts of the number of codons used.  For
example:

  use SeqStats;
  $seq_stats  = Bio::Tools::SeqStats->new($seqobj);
  $weight = $seq_stats->get_mol_wt();
  $monomer_ref = $seq_stats->count_monomers();
  $codon_ref = $seq_stats->count_codons();  # for nucleic acid sequence

Note: sometimes sequences will contain ambiguous codes.  For this
reason, get_mol_wt() returns a reference to a two element array
containing a greatest lower bound and a least upper bound of the
molecular weight.

The SeqWords object is similar to SeqStats and provides
methods for calculating frequencies of "words" (e.g. tetramers or hexamers)
within the sequence. See L<Bio::Tools::SeqStats> and L<Bio::Tools::SeqWords>
for more information.

=head2 III.3.3 Identifying restriction enzyme sites (Bio::Restriction)

Another common sequence manipulation task for nucleic acid sequences
is locating restriction enzyme cutting sites.  Bioperl provides the
Bio::Restriction::Enzyme, Bio::Restriction::EnzymeCollection, and
Bio::Restriction::Analysis objects for this purpose. These modules replace the
older module Bio::Tools::RestrictionEnzyme. A new collection of enzyme
objects would be defined like this:

   use Bio::Restriction::EnzymeCollection;
   my $all_collection = Bio::Restriction::EnzymeCollection;

Bioperl's default Restriction::EnzymeCollection object comes with data for 
more than 500 different Type II restriction enzymes. A list of the available 
enzyme names can be accessed using the available_list() method, but these 
are just the names, not the functional objects. You also have access to 
enzyme subsets. For example to select all available Enzyme objects with 
recognition sites that are six bases long one could write:

  my $six_cutter_collection = $all_collection->cutters(6);
  foreach my $enz ($six_cutter_collection){
     print $enz->name,"\t",$enz->site,"\t",$enz->overhang_seq,"\n";
     # prints name, recognition site, overhang
  }

There are other methods that can be used to select sets of enzyme objects,
such as unique_cutters() and blunt_enzymes(). You can also select a
Enzyme object by name, like so:

  my $ecori_enzyme = $all_collection->get_enzyme('EcoRI');

Once an appropriate enzyme has been selected, the sites for that
enzyme on a given nucleic acid sequence can be obtained using the
fragments() method.  The syntax for performing this task is:

   use Bio::Restriction::Analysis;
   my $analysis = Bio::Restriction::Analysis->new(-seq => $seq);
   # where $seq is the Bio::Seq object for the DNA to be cut
   @fragments =  $analysis->fragments($enzyme);
   # and @fragments will be an array of strings

To get information on isoschizomers, methylation sites, microbe source,
vendor or availability you will need to create your EnzymeCollection 
directly from a REBASE file, like this:

  use Bio::Restriction::IO;
  my $re_io = Bio::Restriction::IO->new(-file=>$file,-format=>'withrefm');
  my $rebase_collection = $re_io->read;

A REBASE file in the correct format can be found at 
ftp://ftp.neb.com/pub/rebase, it will have a name like "withrefm.308".
If need be you can also create new enzymes, like this:

  my $re = new Bio::Restriction::Enzyme(-enzyme=>'BioRI',-seq=>'GG^AATTCC');

For more informatation see L<Bio::Restriction::Enzyme>,
L<Bio::Restriction::EnzymeCollection>, L<Bio::Restriction::Analysis>, and
L<Bio::Restriction::IO>.

=head2    III.3.4 Identifying amino acid cleavage sites (Sigcleave)

For amino acid sequences we may be interested to know whether the
amino acid sequence contains a cleavable signal sequence for
directing the transport of the protein within the cell.  SigCleave is
a program (originally part of the EGCG molecular biology package) to
predict signal sequences, and to identify the cleavage site based on
the von Heijne algorithm.

The threshold setting controls the score reporting.  If no value for
threshold is passed in by the user, the code defaults to a reporting
value of 3.5.  SigCleave will only return score/position
pairs which meet the threshold limit.

There are 2 accessor methods for this object. signals() will return a
perl hash containing the sigcleave scores keyed by amino acid
position. pretty_print() returns a formatted string similar to the
output of the original sigcleave utility.

The syntax for using Sigcleave is as follows:

  # create a Seq object, for example:
  $seqobj = Bio::Seq->new(-seq => "AALLHHHHHHGGGGPPRTTTTTVVVVVVVVVVVVVVV");

  use Bio::Tools::Sigcleave;
  $sigcleave_object = new Bio::Tools::Sigcleave
      ( -seq       => $seqobj,
        -threshold => 3.5,
        -desc      => 'test sigcleave protein seq',
        -type      => 'AMINO'
      );
  %raw_results      = $sigcleave_object->signals;
  $formatted_output = $sigcleave_object->pretty_print;

Note that the "type" in the Sigcleave object is "amino"
whereas in a Seq object it would be called "protein". Please see
L<Bio::Tools::Sigcleave> for details.


=head2 III.3.5 Miscellaneous sequence utilities: OddCodes, SeqPattern

OddCodes:

For some purposes it's useful to have a listing of an amino acid
sequence showing where the hydrophobic amino acids are located or
where the positively charged ones are.  Bioperl provides this
capability via the module Bio::Tools::OddCodes.

For example, to quickly see where the charged amino acids are located
along the sequence we perform:

  use Bio::Tools::OddCodes;
  $oddcode_obj = Bio::Tools::OddCodes->new($amino_obj);
  $output = $oddcode_obj->charge();

The sequence will be transformed into a three-letter sequence (A,C,N)
for negative (acidic), positive (basic), and neutral amino acids.  For
example the ACDEFGH would become NNAANNC.

For a more complete chemical description of the sequence one can call
the chemical() method which turns sequence into one with an 8-letter
chemical alphabet { A (acidic), L (aliphatic), M (amide), R
(aromatic), C (basic), H (hydroxyl), I (imino), S (sulfur) }:

  $output = $oddcode_obj->chemical();

In this case the sample sequence ACDEFGH would become LSAARAC.

OddCodes also offers translation into alphabets showing alternate
characteristics of the amino acid sequence such as hydrophobicity,
"functionality" or grouping using Dayhoff's definitions.  See the
documentation in L<Bio::Tools::OddCodes> for further details.

SeqPattern:

The SeqPattern object is used to manipulate sequences
using perl regular expressions.  A key motivation for
SeqPattern is to have a way of generating a reverse complement of a
nucleic acid sequence pattern that includes ambiguous bases and/or
regular expressions.  This capability leads to significant performance
gains when pattern matching on both the sense and anti-sense strands
of a query sequence are required. Typical syntax for using SeqPattern
is shown below.  For more information, there are several interesting
examples in the script seq_pattern.pl in the examples/tools directory.

  use Bio::Tools::SeqPattern;
  $pattern     = '(CCCCT)N{1,200}(agggg)N{1,200}(agggg)';
  $pattern_obj = new Bio::Tools::SeqPattern(-SEQ  => $pattern,
                                            -TYPE => 'dna');
  $pattern_obj2 = $pattern_obj->revcom();
  $pattern_obj->revcom(1); # returns expanded rev complement pattern.

More detail can be found in L<Bio::Tools::SeqPattern>.


=for html <A NAME ="iii.3.6"></A>

=head2 III.3.6 Converting coordinate systems (Coordinate::Pair, RelSegment)

Coordinate system conversion is a common requirement, for example, when 
one wants to look at the relative positions of sequence features to one 
another and convert those relative positions to absolute coordinates 
along a chromosome or contig.  Although coordinate conversion sounds pretty 
trivial it can get fairly tricky when one includes the possibilities of 
switching to coordinates on negative (i.e. Crick) strands and/or having 
a coordinate system terminate because you have reached the end of a 
clone or contig. Bioperl has two different approaches to coordinate-system 
conversion (based on the modules Bio::Coordinate::Pair and 
Bio::DB::GFF::RelSegment, respectively).

The Coordinate::Pair approach is somewhat more "low level".  With it, you 
define an input coordinate system and an output coordinate system, where 
in each case a coordinate system is a triple of a start position, end position 
and strand.  The end position is especially important when dealing with 
unfinished assemblies where the coordinate system ends when one reaches 
the end of the sequence of a clone or contig.  Once one has defined the 
two coordinate systems, one defines a Coordinate::Pair to map between 
them.  Then one can map positions between the coordinates systems with 
code such as this:

  $input_coordinates = Bio::Location::Simple->new  
  (-seq_id => 'propeptide', -start => 1000, -end => 2000, -strand=>1 );
  $output_coordinates = Bio::Location::Simple->new  
  (-seq_id => 'peptide', -start => 1100, -end => 2100, -strand=>1 );
  $pair = Bio::Coordinate::Pair->new
  (-in => $input_coordinates ,  -out => $output_coordinates   );
  $pos = Bio::Location::Simple->new (-start => 500, -end => 500 );
  $res = $pair->map($pos);
  $converted_start = $res->start;

In this example $res is also a Bio::Location object, as you'd expect.
See the documentation for Bio::Coordinate::Pair and Bio::Coordinate::GeneMapper
for more details.

The Bio::DB::GFF::RelSegment approach is designed more for handling coordinate 
transformations of sequence features rather than for transforming arbitrary 
coordinate systems.  With Bio::DB::GFF::RelSegment you define a coordinate 
system relative to a specific feature (called the "refseq").  You also have 
access to the absolute coordinate system (typically of the entire chromosome.)  
You can determine the position of a feature relative to some other feature 
simply by redefining the relevant reference feature (i.e. the "refseq") with 
code like this:

  $db = Bio::DB::GFF->new(-dsn     => 'dbi:mysql:elegans',
                          -adaptor => 'dbi:mysqlopt');

  $segment = $db->segment('ZK909');
  $relative_start = $segment->start;  # $relative_start = 1;

  # Now retrieve the start position of ZK909 relative to feature ZK337
  $segment->refseq('ZK337');
  $relative_start = $segment->start;

  # Now retrieve the start position of ZK909 relative to the entire chromosome
  $absolute_start =  $segment->abs_start;

This approach is convenient because you don't have to keep track of 
coordinates directly, you just keep track of the name of a feature 
which in turn marks the coordinate-system origin.  However, this 
approach does require that you have stored all the sequence features 
in GFF format. Moreover, Bio::DB::GFF::RelSegment has been principally 
developed and tested for applications where all the sequence features are 
stored in a Bioperl-db relational database. However, if one wants to use 
the Bio:DB::GFF machinery (including its coordinate transformation 
capabilities) without building a local relational database, this is 
possible by defining the 'database' as having an adaptor called 'memory',
e.g. 

  $db = Bio::DB::GFF->new( '-adaptor' => 'memory' );

For more details on coordinate transformations and other GFF-related 
capabilities in Bioperl see L<Bio::DB::GFF::RelSegment>, L<Bio::DB::GFF>,
and the test file t/BioDBGFF.t.

=head2 III.4 Searching for similar sequences

One of the basic tasks in molecular biology is identifying sequences
that are, in some way, similar to a sequence of interest.  The Blast
programs, originally developed at the NCBI, are widely used for
identifying such sequences.  The bioperl and bioperl-run packages
offer a number of modules to facilitate running Blast as well as to
parse the often voluminous reports produced by Blast.

=head2   III.4.1 Running BLAST (using RemoteBlast.pm)

Bioperl supports remote execution of blasts at NCBI by means of the
RemoteBlast object.

A skeleton script to run a remote blast might look as follows:

  $remote_blast = Bio::Tools::Run::RemoteBlast->new (
  	   -prog => 'blastp',-data => 'ecoli',-expect => '1e-10' );
  $r = $remote_blast->submit_blast("t/data/ecolitst.fa");
  while (@rids = $remote_blast->each_rid ) {
      foreach $rid ( @rids ) {$rc = $remote_blast->retrieve_blast($rid);}
  }

You may want to change some parameter of the remote job and this example
shows how to change the matrix:

  $Bio::Tools::Run::RemoteBlast::HEADER{'MATRIX_NAME'} = 'BLOSUM25';

For a description of the many CGI parameters see:

  http://www.ncbi.nlm.nih.gov/BLAST/Doc/urlapi.html

Note that the script has to be broken into two parts. The actual Blast
submission and the subsequent retrieval of the results. At times when the
NCBI Blast is being heavily used, the interval between when a Blast
submission is made and when the results are available can be substantial.

The object $rc would contain the blast report that could then be parsed with
Bio::Tools::BPlite or Bio::SearchIO. The default object returned is 
SearchIO after version 1.0. The object type can be changed using the 
-readmethod parameter but bear in mind that the favored Blast parser is 
Bio::SearchIO, others won't be supported in later versions.

Note that to make this script actually useful, one should add details
such as checking return codes from the Blast to see if it succeeded and
a "sleep" loop to wait between consecutive requests to the NCBI server.
See example 22 in the demonstration script in the appendix to see some
working code you could use, or L<Bio::Tools::Run::RemoteBlast> for
details.

It should also be noted that the syntax for creating a remote blast factory
is slightly different from that used in creating StandAloneBlast, Clustalw,
and T-Coffee factories.  Specifically RemoteBlast requires parameters to
be passed with a leading hyphen, as in '-prog' =E<gt> 'blastp', while the
other programs do not pass parameters with a leading hyphen.

=for html <A NAME ="iii.4.2"></A>

=head2    III.4.2 Parsing BLAST and FASTA reports with Search and SearchIO

No matter how Blast searches are run (locally or remotely, with or
without a perl interface), they return large quantities of data that
are tedious to sift through.  Bioperl offers several different objects
- Search.pm/SearchIO.pm, and BPlite.pm (along with its minor
modifications, BPpsilite and BPbl2seq) for parsing Blast reports.
Search and SearchIO which are the principal Bioperl interfaces for
Blast and FASTA report parsing, are described in this section.  The
older BPlite is described in section L<"III.4.3">. We recommend you
use SearchIO, it's certain to be supported in future releases.

The Search and SearchIO modules provide a uniform interface for
parsing sequence-similarity-search reports generated by BLAST (in
standard and BLAST XML formats), PSI-BLAST, RPS-BLAST, bl2seq and FASTA. 
The SearchIO modules also provide a parser for HMMER reports and in
the future, it is envisioned that the Search/SearchIO syntax will be
extended to provide a uniform interface to an even wider range of report
parsers including parsers for Genscan.

Parsing sequence-similarity reports with Search and SearchIO is
straightforward.  Initially a SearchIO object specifies a file
containing the report(s). The method next_result reads the next report
into a Search object in just the same way that the next_seq method of
SeqIO reads in the next sequence in a file into a Seq object.

Once a report (i.e. a SearchIO object) has been read in and is available
to the script, the report's overall attributes (e.g. the query) can be
determined and its individual hits can be accessed with the
next_hit method.  Individual high-scoring segment pairs for each hit
can then be accessed with the next_hsp method. Except for
the additional syntax required to enable the reading of multiple
reports in a single file, the remainder of the Search/SearchIO parsing
syntax is very similar to that of the BPlite object it is intended to replace.
Sample code to read a BLAST report might look like this:

  # Get the report
  $searchio = new Bio::SearchIO (-format => 'blast',
				 -file   => $blast_report);
  $result = $searchio->next_result;

  # Get info about the entire report
  $result->database_name;
  $algorithm_type =  $result->algorithm;

  # get info about the first hit
  $hit = $result->next_hit;
  $hit_name = $hit->name ;

  # get info about the first hsp of the first hit
  $hsp = $hit->next_hsp;
  $hsp_start = $hsp->query->start;

For more details there is a good description of how to use
SearchIO at http://www.bioperl.org/HOWTOs/html/SearchIO.html
or in the docs/howto subdirectory of the distribution. Additional
documentation can be found in L<Bio::SearchIO::blast>,
L<Bio::SearchIO::psiblast>, L<Bio::SearchIO::blastxml>,
L<Bio::SearchIO::fasta>, and L<Bio::SearchIO>. There is also sample
code in the examples/searchio directory which illustrates how to
use SearchIO. And finally, there's a section with SearchIO questions
in the FAQ (http://bioperl.org/Core/Latest/faq.html#3).

=for html <A NAME ="iii.4.3"></A>

=head2 III.4.3 Parsing BLAST reports with BPlite, BPpsilite, and BPbl2seq

Bioperl's older BLAST report parsers - BPlite, BPpsilite, BPbl2seq and
Blast.pm - are no longer supported but since legacy Bioperl scripts have 
been written which use these objects, they are likely to remain within 
Bioperl for some time.

Much of the user interface of BPlite is very similar to that of Search.
However accessing the next hit or HSP uses methods called next_Sbjct and
next_HSP, respectively - in contrast to Search's next_hit and next_hsp.


BPlite

The syntax for using BPlite is as follows where the method
for retrieving hits is now called nextSbjct() (for "subject"), while the
method for retrieving high-scoring-pairs is called nextHSP():

  use Bio::Tools::BPlite;
  $report = new Bio::Tools::BPlite(-fh=>\*STDIN);
  $report->query;
  while(my $sbjct = $report->nextSbjct) {
       $sbjct->name;
       while (my $hsp = $sbjct->nextHSP) { print $hsp->score,"\n"; }
  }

A complete description of the module can be found in L<Bio::Tools::BPlite>.

BPpsilite

BPpsilite and BPbl2seq are objects for parsing (multiple iteration)
PSIBLAST reports and Blast bl2seq reports, respectively.  They are
both minor variations on the BPlite object. See L<Bio::Tools::BPbl2seq>
and L<Bio::Tools::BPpsilite> for details.

The syntax for parsing a multiple iteration PSIBLAST report is as
shown below.  The only significant additions to BPlite are methods to
determine the number of iterated blasts and to access the results from
each iteration.  The results from each iteration are parsed in the
same manner as a (complete) BPlite object.

  use Bio::Tools::BPpsilite;
  $report = new Bio::Tools::BPpsilite(-fh=>\*STDIN);
  $total_iterations = $report->number_of_iterations;
  $last_iteration = $report->round($total_iterations)
  while(my $sbjct =  $last_iteration ->nextSbjct) {
       $sbjct->name;
       while (my $hsp = $sbjct->nextHSP) {$hsp->score; }
  }

See L<Bio::Tools::BPpsilite> for details.

BPbl2seq

BLAST bl2seq is a program for comparing and aligning two sequences
using BLAST.  Although the report format is similar to that of a
conventional BLAST, there are a few differences.  Consequently, the
standard bioperl parser BPlite ia unable to read bl2seq
reports directly. From the user's perspective, one difference
between bl2seq and other blast reports is that the bl2seq report does
not print out the name of the first of the two aligned sequences.
Consequently, BPbl2seq has no way of identifying the name of one of
the initial sequence unless it is explicitly passed to constructor as
a second argument as in:

  use Bio::Tools::BPbl2seq;
  $report = Bio::Tools::BPbl2seq->new(-file => "t/data/dblseq.out",
                                      -queryname => "ALEU_HORVU");
  $hsp = $report->next_feature;
  $answer=$hsp->score;

In addition, since there will only be (at most) one subject (hit) in a
bl2seq report one should use the method $report-E<gt>next_feature,
rather than $report-E<gt>nextSbjct-E<gt>nextHSP to obtain the next high
scoring pair. See L<Bio::Tools::BPbl2seq> for more details.

Blast.pm

The Bio::Tools::Blast parser has been removed from Bioperl as of version
1.1. Consequently, the BPlite parser (described in the
section L<"III.4.3">) or the Search/SearchIO parsers (section L<"III.4.2">)
should be used for BLAST parsing within bioperl. SearchIO is the preferred
approach and will be formally supported in future releases.

=for html <A NAME ="iii.4.4"></A>

=head2 III.4.4 Parsing HMM reports (HMMER::Results, SearchIO)

Blast is not the only sequence-similarity-searching program supported
by bioperl. HMMER is a Hidden Markov Model (HMM) program that
(among other capabilities) enables sequence similarity searching, from
http://hmmer.wustl.edu. Bioperl does not currently provide a perl interface
for running HMMER.  However, bioperl does provide 2 HMMER report parsers,
the recommended SearchIO HMMER parser and an older parser called HMMER::Results.

SearchIO can parse reports generated both by the HMMER program
hmmsearch - which searches a sequence database for sequences similar
to those generated by a given HMM - and the program hmmpfam - which
searches a HMM database for HMMs which match domains of a given
sequence.  Sample usage for parsing a hmmsearch report might be:

  use Bio::SearchIO;

  $in = new Bio::SearchIO(-format => 'hmmer',-file => '123.hmmsearch');
  while ( $res = $in->next_result ){
    # get a Bio::Search::Result::HMMERResult object
    print $res->query_name, " for HMM ", $res->hmm_name, "\n";
    while ( $hit = $res->next_hit ){
      print $hit->name, "\n";
      while ( $hsp = $hit->next_hsp ){
        print "length is ", $hsp->length, "\n";
      }
    }
  }

Purists may insist that the term "hsp" is not applicable to hmmsearch or
hmmpfam results and they may be correct - this is an unintended
consequence of using the flexible and extensible SearchIO approach. See
L<Bio::Search::Result::HMMERResult> for more information.

For documentation on the older, unsupported HMMER parser, look at 
L<Bio::Tools::HMMER::Results>.

=for html <A NAME ="iii.4.5"></A>

=head2 III.4.5 Running BLAST locally  (StandAloneBlast)

There are several reasons why one might want to run the Blast programs
locally - speed, data security, immunity to network problems, being
able to run large batch runs, wanting to use custom or proprietary
databases, etc.  The NCBI provides a downloadable version of blast in
a stand-alone format, and running blast locally without any use of
perl or bioperl is completely straightforward.  However, there are
situations where having a perl interface for running the blast
programs locally is convenient.

The module Bio::Tools::Run::StandAloneBlast offers the ability to wrap
local calls to blast from within perl.  All of the currently available
options of NCBI Blast (e.g. PSIBLAST, PHIBLAST, bl2seq) are available
from within the bioperl StandAloneBlast interface.  Of course, to use
StandAloneBlast, one needs to have installed BLAST from NCBI locally as
well as one or more blast-readable databases.

Basic usage of the StandAloneBlast.pm module is simple.  Initially, a
local blast factory object is created.

  @params = (program  => 'blastn',
             database => 'ecoli.nt');
  $factory = Bio::Tools::Run::StandAloneBlast->new(@params);

Any parameters not explicitly set will remain as the BLAST defaults.
Once the factory has been created and the appropriate parameters set,
one can call one of the supported blast executables.  The input
sequence(s) to these executables may be fasta file(s), a Seq
object or an array of Seq objects, eg

  $input = Bio::Seq->new(-id  =>"test query",
  			 -seq =>"ACTAAGTGGGGG");
  $blast_report = $factory->blastall($input);

The returned blast report will be in the form of a bioperl
parsed-blast object.  The report object may be either a SearchIO, BPlite,
BPpsilite, BPbl2seq or Blast object depending on the type of blast
search - the SearchIO object is returned by default.  The raw blast
report is also available.

The syntax for running PHIBLAST, PSIBLAST and bl2seq searches via
StandAloneBlast is also straightforward.  See
L<Bio::Tools::Run::StandAloneBlast> documentation for details. In
addition, the script standaloneblast.pl in the examples/tools directory
contains descriptions of various possible applications of the
StandAloneBlast object. This script shows how the blast report object
can access the SearchIO blast parser directly, e.g.

  while (my $hit = $blast_report->next_hit){
     while (my $hsp = $sbjct->next_hsp){
        print $hsp->score," ",$hit->name,"\n";
     }
  }

See the sections L<"III.4.2"> and L<"III.4.3"> for more details on
parsing BLAST reports.

=for html <A NAME ="iii.5"></A>

=head2 III.5 Manipulating sequence alignments (SimpleAlign)

Once one has identified a set of similar sequences, one often needs to
create an alignment of those sequences. Bioperl offers several perl
objects to facilitate sequence alignment: pSW, Clustalw.pm, TCoffee.pm
and the bl2seq option of StandAloneBlast. As of release 1.2 of
bioperl, using these modules (except bl2seq) requires a bioperl
auxiliary library (bioperl-ext for pSW, bioperl-run for the others)
and are therefore described in section IV. Here we describe only the
module within the bioperl core package for manipulating previously
created alignments, namely the SimpleAlign module.

The script aligntutorial.pl in the examples/align/ subdirectory is
another good source of information of ways to create and manipulate
sequence alignments within bioperl.

SimpleAlign objects are produced by bioperl-run alignment creation objects
(e.g. Clustalw.pm, BLAST's bl2seq, TCoffee.pm, Lagan.pm, or pSW from 
the bioperl-ext package) or they can be read in from files of 
multiple-sequence alignments in various formats using AlignIO.

Some of the manipulations possible with SimpleAlign include:

=over 4

=item *

slice(): Obtaining an alignment "slice", that is, a subalignment inclusive of
specified start and end columns.  Sequences with no residues in the slice are
excluded from the new alignment and a warning is printed.

=item *

column_from_residue_number(): Finding column in an alignment where a specified
residue of a specified sequence is located.

=item *

consensus_string(): Making a consensus string. This method includes an
optional threshold parameter, so that positions in the alignment with lower
percent-identity than the threshold are marked by "?"'s in the consensus

=item *

percentage_identity(): A fast method for calculating the average percentage
identity of the alignment

=item *

consensus_iupac(): Making a consensus using IUPAC ambiguity codes from
DNA and RNA.


=back

Skeleton code for using some of these features is shown below.  More detailed,
working code is in bptutorial.pl example 13 and in align_on_codons.pl in the
examples/align directory. Additional documentation on methods can be found in
L<Bio::SimpleAlign> and L<Bio::LocatableSeq>.

  use Bio::SimpleAlign;
  $aln = Bio::SimpleAlign->new('t/data/testaln.dna');
  $threshold_percent = 60;
  $consensus_with_threshold = $aln->consensus_string($threshold_percent);
  $iupac_consensus = $aln->consensus_iupac();   # dna/rna alignments only
  $percent_ident = $aln->percentage_identity;
  $seqname = '1433_LYCES';
  $pos = $aln->column_from_residue_number($seqname, 14);

=head2 III.6 Searching for genes and other structures on genomic DNA (Genscan, Sim4, Grail, Genemark, ESTScan, MZEF, EPCR)

Automated searching for putative genes, coding sequences,
sequence-tagged-sites (STS's) and other functional
units in genomic and expressed sequence tag (EST) data has
become very important as the available quantity of sequence data has
rapidly increased.  Many feature searching programs currently exist.
Each produces reports containing predictions that must be read
manually or parsed by automated report readers.

Parsers for six widely used gene prediction programs - Genscan, Sim4,
Genemark, Grail, ESTScan and MZEF - are available in bioperl. The
interfaces for these parsers are all similar.  We illustrate the usage
for Genscan and Sim4 here.  The syntax is relatively self-explanatory;
see L<Bio::Tools::Genscan>, L<Bio::Tools::Genemark>,
L<Bio::Tools::Grail>, L<Bio::Tools::ESTScan>, L<Bio::Tools::MZEF>, and
L<Bio::Tools::Sim4::Results> for further details.

  use Bio::Tools::Genscan;
  $genscan = Bio::Tools::Genscan->new(-file => 'result.genscan');
  # $gene is an instance of Bio::Tools::Prediction::Gene
  # $gene->exons() returns an array of Bio::Tools::Prediction::Exon objects
  while($gene = $genscan->next_prediction())
      { @exon_arr = $gene->exons(); }
  $genscan->close();

See L<Bio::Tools::Prediction::Gene> and L<Bio::Tools::Prediction::Exon>
for more details.

  use Bio::Tools::Sim4::Results;
  $sim4 = new Bio::Tools::Sim4::Results(-file => 't/data/sim4.rev',
                                        -estisfirst => 0);
  # $exonset is-a Bio::SeqFeature::Generic with Bio::Tools::Sim4::Exons
  # as sub features
  $exonset = $sim4->next_exonset;
  @exons = $exonset->sub_SeqFeature();
  # $exon is-a Bio::SeqFeature::FeaturePair
  $exon = 1;
  $exonstart = $exons[$exon]->start();
  $estname = $exons[$exon]->est_hit()->seqname();
  $sim4->close();

See L<Bio::SeqFeature::Generic> and L<Bio::Tools::Sim4::Exons> for more
information.

A parser for the ePCR program is also available. The ePCR program identifies
potential PCR-based sequence tagged sites (STSs)
For more details see the documentation in L<Bio::Tools::EPCR>.
A sample skeleton script for parsing an ePCR report and using the data to
annotate a genomic sequence might look like this:

  use Bio::Tools::EPCR;
  use Bio::SeqIO;
  $parser = new Bio::Tools::EPCR(-file => 'seq1.epcr');
  $seqio = new Bio::SeqIO(-format => 'fasta', -file => 'seq1.fa');
  $seq = $seqio->next_seq;
  while( $feat = $parser->next_feature ) {
        # add EPCR annotation to a sequence
        $seq->add_SeqFeature($feat);
  }

=for html <A NAME ="iii.7"></A>

=head2 III.7 Developing machine readable sequence annotations

Historically, annotations for sequence data have been entered and read
manually in flat-file or relational databases with relatively little
concern for machine readability.  More recent projects - such as EBI's
ENSEMBL project and the efforts to develop an XML molecular biology
data specification - have begun to address this limitation.  Because
of its strengths in text processing and regular-expression handling,
perl is a natural choice for the computer language to be used for this
task.  And bioperl offers numerous tools to facilitate this process -
several of which are described in the following sub-sections.

=for html <A NAME ="iii.7.1"></A>

=head2 III.7.1 Representing sequence annotations (SeqFeature,RichSeq,Location)

In Bioperl, most sequence annotations are stored in sequence-feature
(SeqFeature) objects, where the SeqFeature object is associated with a
parent Seq object.  A SeqFeature object generally has a
description (e.g. "exon", "promoter"), a location specifying its
start and end positions on the parent sequence, and a reference to its 
parent sequence. In addition, a Seq object can also have an
Annotation object associated with it, which could be used to store database 
links, literature references and comments. Creating a new SeqFeature and
Annotation and associating it with a Seq is accomplished with syntax
like:

  $feat = new Bio::SeqFeature::Generic(-start   => 40,
  				       -end     => 80,
  				       -strand  => 1,
  				       -primary => 'exon',
  				       -source  => 'internal' );
  $seqobj->add_SeqFeature($feat); # Add the SeqFeature to the Seq object

Once the features and annotations have been associated with the Seq,
they can be with retrieved, eg:

  @topfeatures = $seqobj->top_SeqFeatures(); # just top level, or
  @allfeatures = $seqobj->all_SeqFeatures(); # descend into sub features
  $disease_annotation = $annotations->get_Annotations('disease');

The individual components of a SeqFeature can also be set or retrieved
with methods including:

  # methods which return numbers
  $feat->start          # start position
  $feat->end            # end position

  $feat->strand         # 1 means forward, -1 reverse, 0 not relevant

  # methods which return strings
  $feat->primary_tag    # the main 'name' of the sequence feature,
                        # eg, 'exon'
  $feat->source_tag     # where the feature comes from, e.g. 'BLAST'

  # methods which return Bio::PrimarySeq objects
  $feat->seq            # the sequence between start and end
  $feat->entire_seq     # the entire sequence
  $feat->spliced_seq    # the "joined" sequence, when there are
                        # multiple sub-locations

  # other useful methods include
  $feat->overlap($other)  # do SeqFeature $feat and SeqFeature $other overlap?
  $feat->contains($other) # is $other completely within $feat?
  $feat->equals($other)   # do $feat and $other completely agree?
  $feat->sub_SeqFeatures  # create/access an array of subsequence features

It is worth mentioning that one can also retrieve the start and end
positions of a feature using a Bio::LocationI object:

  $location = $feat->location # $location is a Bio::LocationI object
  $location->start;           # start position
  $location->end;             # end position

This is useful because one can use a Bio::Location::SplitLocationI object
in order to retrieve the split coordinates inside the Genbank or EMBL join()
statements (e.g. "CDS    join(51..142,273..495,1346..1474)"):

  if ( $feat->location->isa('Bio::Location::SplitLocationI') &&
	       $feat->primary_tag eq 'CDS' )  {
    foreach $loc ( $feat->location->sub_Location ) {
      print $loc->start,"..",$loc->end,"\n";
    }
  }

See L<Bio::LocationI> and L<Bio::Location::SplitLocationI> for more
information.

If more detailed information is required than is currently available in Seq
objects the RichSeq object may be used. It is applicable in particular to
database sequences (EMBL, GenBank and Swissprot) with detailed annotations.
Sample usage might be:

    @secondary   = $richseq->get_secondary_accessions;
    $division    = $richseq->division;
    @dates       = $richseq->get_dates;
    $seq_version = $richseq->seq_version;

See L<Bio::Seq::RichSeqI> for more details.

=head2 III.7.2 Representing sequence annotations (Annotation::Collection)

Much of the interesting description of a sequence can be associated with
sequence features but in sequence objects derived from Genbank or EMBL entries
there can be useful information in other "annotation" sections, such as the 
COMMENTS section of a Genbank entry. In order to access this information 
you'll need to create an Annotation::Collection object. For example:

  $db = new Bio::DB::GenBank;
  $seqobj = $db->get_Seq_by_acc("NM_125788");
  $ann_coll = $seqobj->annotation;

This Collection object is just a container for other specialized objects, and 
its methods are described in L<Bio::Annotation::Collection>. You can find the 
desired object within the Collection object by examining the "tagnames":

  foreach $ann ($ann_coll->get_Annotations) {
    print "Comment: ",$ann->as_text if ($ann->tagname eq "comment");
  }

Other possible tagnames include "date_changed", "keyword", and "reference". 
Objects with the "reference" tagname are Bio::Annotation::Reference objects 
and represent scientific articles. See L<Bio::Annotation::Reference> for 
descriptions of the methods used to access the data in Reference objects.
There is also a HOWTO on features and annotation 
(http://bioperl.org/HOWTOs/html/Feature-Annotation.html).

=for html <A NAME ="iii.7.3"></A>

=head2 III.7.3 Representing large sequences (LargeSeq)

Very large sequences present special problems to automated sequence-annotation 
storage and retrieval projects.  Bioperl's LargeSeq object addresses this
situation.

A LargeSeq object is a SeqI compliant object that stores a sequence as
a series of files in a temporary directory (see sect L<"II.1"> or
L<Bio::SeqI> for a definition of SeqI objects). The aim is to enable
storing very large sequences (e.g. E<gt> 100 MBases) without running out
of memory and, at the same time, preserving the familiar bioperl Seq
object interface. As a result, from the user's perspective, using a
LargeSeq object is almost identical to using a Seq object. The
principal difference is in the format used in the SeqIO calls. Another
difference is that the user must remember to only read in small chunks
of the sequence at one time.  These differences are illustrated in the
following code:

  $seqio = new Bio::SeqIO(-format => 'largefasta',
  			  -file   => 't/data/genomic-seq.fasta');
  $pseq = $seqio->next_seq();
  $plength = $pseq->length();
  $last_4 = $pseq->subseq($plength-3,$plength);  # this is OK

  # On the other hand, the next statement would
  # probably cause the machine to run out of memory
  # $lots_of_data = $pseq->seq();  # NOT OK for a large LargeSeq object

=head2 III.7.4 Representing changing sequences (LiveSeq)

Data files with sequences that are frequently being updated present special
problems to automated sequence-annotation storage and retrieval projects.
Bioperl's LiveSeq object is designed to address this situation.

The LiveSeq object addresses the need for a sequence object capable of
handling sequence data that may be changing over time.  In such a
sequence, the precise locations of features along the sequence may
change.  LiveSeq deals with this issue by re-implementing the sequence
object internally as a "double linked chain." Each element of the
chain is connected to other two elements (the PREVious and the NEXT
one). There is no absolute position like in an array, hence if
positions are important, they need to be computed (methods are
provided). Otherwise it's easy to keep track of the elements with
their "LABELs". There is one LABEL (think of it as a pointer) to each
ELEMENT. The labels won't change after insertions or deletions of the
chain. So it's always possible to retrieve an element even if the
chain has been modified by successive insertions or deletions.

Although the implementation of the LiveSeq object is novel, its
bioperl user interface is unchanged since LiveSeq implements a
PrimarySeqI interface (recall PrimarySeq is the subset of Seq without
annotations or SeqFeatures - see section L<"II.1"> or L<Bio::PrimarySeq>).
Consequently syntax for using LiveSeq objects is familiar although a
modified version of SeqIO called Bio::LiveSeq::IO::Bioperl needs to be
used to actually load the data, e.g.:

  $loader = Bio::LiveSeq::IO::BioPerl->load(-db   => "EMBL",
                                            -file => "t/data/factor7.embl");
  $gene = $loader->gene2liveseq(-gene_name => "factor7");
  $id = $gene->get_DNA->display_id ;
  $maxstart = $gene->maxtranscript->start;

See L<Bio::LiveSeq::IO::BioPerl> for more details.

=head2 III.7.5 Representing related sequences - mutations, polymorphisms (Allele, SeqDiff)

A Mutation object allows for a basic description of a sequence change
in the DNA sequence of a gene. The Mutator object takes in mutations,
applies them to a LiveSeq gene and returns a set of Bio::Variation
objects describing the net effect of the mutation on the gene at the DNA,
RNA and protein level.

The objects in Bio::Variation and Bio::LiveSeq directory were
originally designed for the "Computational Mutation Expression
Toolkit" project at European Bioinformatics Institute (EBI). The
result of using them to mutate a gene is a holder object, 'SeqDiff',
that can be printed out or queried for specific information. For
example, to find out if restriction enzyme changes caused by a
mutation are exactly the same in DNA and RNA sequences, we can write:

  use Bio::LiveSeq::IO::BioPerl;
  use Bio::LiveSeq::Mutator;
  use Bio::LiveSeq::Mutation;

  $loader = Bio::LiveSeq::IO::BioPerl->load(-file => "$filename");
  $gene = $loader->gene2liveseq(-gene_name => $gene_name);
  $mutation = new Bio::LiveSeq::Mutation (-seq =>'G',
  					  -pos => 100 );
  $mutate = Bio::LiveSeq::Mutator->new(-gene      => $gene,
  				       -numbering => "coding"  );
  $mutate->add_Mutation($mutation);
  $seqdiff = $mutate->change_gene();
  $DNA_re_changes = $seqdiff->DNAMutation->restriction_changes;
  $RNA_re_changes = $seqdiff->RNAChange->restriction_changes;
  $DNA_re_changes eq $RNA_re_changes or print "Different!\n";

For a complete working script, see the change_gene.pl script
in the examples/liveseq directory. For more details on the use of these objects
see L<Bio::LiveSeq::Mutator> and L<Bio::LiveSeq::Mutation> as well as
the original documentation for the "Computational Mutation Expression
Toolkit" project at http://www.ebi.ac.uk/mutations/toolkit/.

=for html <A NAME ="iii.7.6"></A>

=head2 III.7.6 Incorporating quality data in sequence annotation (SeqWithQuality)

SeqWithQuality objects are used to describe sequences with very
specific annotations - that is, data quality annotations.  Data quality
information is important for documenting the reliability of base
calls in newly sequenced or otherwise questionable sequence
data. The quality data is contained within a Bio::Seq::PrimaryQual object.
Syntax for using SeqWithQuality objects is as follows:

  # first, make a PrimarySeq object
  $seqobj = Bio::PrimarySeq->new( -seq => 'atcgatcg',
                                  -id  => 'GeneFragment-12',
	                          -accession_number => 'X78121',
                                  -alphabet => 'dna');
  # now make a PrimaryQual object
  $qualobj = Bio::Seq::PrimaryQual->new(-qual => '10 20 30 40 50 50 20 10',
                                        -id   => 'GeneFragment-12',
	                                -accession_number => 'X78121',
                                        -alphabet => 'dna');
  # now make the SeqWithQuality object
  $swqobj = Bio::Seq::SeqQithQuality->new(-seq  => $seqobj,
                                          -qual => $qualobj);
  # Now we access the sequence with quality object
  $swqobj->id(); # the id of the SeqWithQuality object may not match the
                 # id of the sequence or of the quality
  $swqobj->seq(); # the sequence of the SeqWithQuality object
  $swqobj->qual(); # the quality of the SeqWithQuality object

A SeqWithQuality object is created automatically when phred output, a *phd
file, is read by SeqIO, e.g.

  $seqio = Bio::SeqIO->new(-file=>"my.phd",-format=>"phd");
  # or just 'Bio::SeqIO->new(-file=>"my.phd")'
  $seqWithQualObj = $seqio->next_seq;

See L<Bio::Seq::SeqWithQuality> for a detailed description of the methods,
L<Bio::Seq::PrimaryQual>, and L<Bio::SeqIO::phd>.


=head2 III.7.7 Sequence XML representations - generation and parsing (SeqIO::game, SeqIO::bsml)

The previous subsections have described tools for automated sequence
annotation by the creation of an object layer on top of a
traditional database structure. XML takes a somewhat different
approach. In XML, the data structure is unmodified, but machine
readability is facilitated by using a data-record syntax with special
flags and controlled vocabulary.

In order to transfer data with XML in biology, one needs an agreed
upon a vocabulary of biological terms. Several of these have been
proposed and bioperl has at least some support for three: GAME, BSML
and AGAVE.

Once a vocabulary is agreed upon, it becomes possible to convert
sequence XML sequence features can be turned into bioperl
Annotation and SeqFeature objects.  Conversely Seq object features
and annotations can be converted to XML so that they become available
to any other systems.  Typical usage with GAME or BSML are shown
below. No special syntax is required by the user. Note that some Seq
annotation will be lost when using XML in this manner since generally
XML does not support all the annotation information available in Seq
objects.

  $str = Bio::SeqIO->new(-file   => 't/data/test.game',
  			 -format => 'game');
  $seq = $str->next_primary_seq();
  $id = $seq->id;
  @feats = $seq->all_SeqFeatures();
  $first_primary_tag = $feats[0]->primary_tag;

  $str = Bio::SeqIO->new(-file   => 'bsmlfile.xml',
  			 -format => 'bsml');
  $seq = $str->next_primary_seq();
  $id = $seq->id;
  @feats = $seq->all_SeqFeatures();
  $first_primary_tag = $feats[0]->primary_tag;

=head2  III.7.8 Representing Sequences using GFF (Bio:DB:GFF )

Another format for transmitting machine-readable sequence-feature data
is the Genome Feature Format (GFF).  This file type is well suited to
sequence annotation because it allows the ability to describe entries
in terms of parent-child relationships (see
http://www.sanger.ac.uk/software/GFF for details). Bioperl includes a
parser for converting between GFF files and SeqFeature objects.
Typical syntax looks like:

  $gffio = Bio::Tools::GFF->new(-fh => \*STDIN, -gff_version => 2);
    # loop over the input stream
  while ($feature = $gffio->next_feature()) {
    # do something with feature
  }
  $gffio->close();

Further information can be found at L<Bio::Tools::GFF>. Also see
examples/tools/gff2ps.pl, examples/tools/gb_to_gff.pl, and the
scripts in scripts/Bio-DB-GFF. Note: this module shouldn't be confused 
with the module Bio::DB::GFF which is for implementing relational
databases when using bioperl-db.

=head2 III.8 Manipulating clusters of sequences (Cluster, ClusterIO)

Sequence alignments are not the only examples in which one might want
to manipulate a group of sequences together.  Such groups of related 
sequences are generally referred to as clusters.  Examples include
Unigene clusters and gene clusters resulting from clustering
algorithms being applied to microarray data.

The bioperl Cluster and ClusterIO modules are available for handling
sequence clusters.  Currently, cluster input/output modules are
available only for Unigene clusters.  To read in a Unigene cluster (in
the NCBI XML format) and then extract individual sequences for the
cluster for manipulation might look like this:

  my $stream = Bio::ClusterIO->new(-file => "Hs.data", -format => "unigene");
  while ( my $in = $stream->next_cluster ) {
     print $in->unigene_id() . "\n";
     while ( my $sequence = $in->next_seq ) {
        print $sequence->accession_number . "\n";
     }
  }

See L<Bio::Cluster::UniGene> for more details.

=head2  III.9 Representing non-sequence data in Bioperl: structures, trees and maps

Though bioperl has its roots in describing and searching nucleotide and protein
sequences it has also branched out into related fields of study,
such as protein structure, phylogenetic trees and genetic maps.


=head2 III.9.1 Using 3D structure objects and reading PDB files (StructureI, Structure::IO)

A StructureIO object can be created from one or more 3D structures
represented in Protein Data Bank, or pdb, format (see
http://www.rcsb.org/pdb for details).

StructureIO objects allow access to a variety of related Bio:Structure
objects. An Entry object consist of one or more Model objects, which
in turn consist of one or more Chain objects. A Chain is composed of
Residue objects, which in turn consist of Atom objects. There's a
wealth of methods, here are just a few:

  $structio = Bio::Structure::IO->new( -file => "1XYZ.pdb");
  $struc = $structio->next_structure; # returns an Entry object
  $pseq = $struc->seqres;             # returns a PrimarySeq object, thus
  $pseq->subseq(1,20);                # returns a sequence string
  @atoms = $struc->get_atoms($res);   # Atom objects, given a Residue
  @xyz = $atom->xyz;                  # the 3D coordinates of the atom

These lines show how one has access to a number of related objects and methods.
For examples of typical usage of these modules, see the scripts in the
examples/structure subdirectory. Also see L<Bio::Structure::IO>, 
L<Bio::Structure::Entry>, L<Bio::Structure::Model>,
L<Bio::Structure::Chain>, L<Bio::Structure::Residue>, and
L<Bio::Structure::Atom> for more information.

=head2  III.9.2 Tree objects and phylogenetic trees (Tree::Tree, TreeIO, PAML)

Bioperl Tree objects can store data for all kinds of computer trees
and are intended especially for phylogenetic trees.  Nodes and
branches of trees can be individually manipulated.  The TreeIO object
is used for stream I/O of tree objects.  Currently only phylip/newick
tree format is supported.  Sample code might be:

  $treeio = new Bio::TreeIO( -format => 'newick', -file => $treefile);
  $tree = $treeio->next_tree;             # get the tree
  @nodes = $tree->get_nodes;              # get all the nodes
  $tree->get_root_node->each_Descendent;  # get descendents of root node

See L<Bio::TreeIO> and L<Bio::Tree::Tree> for details.

Using the Bio::Tools::Phylo::PAML module one can also parse the
results of the PAML tree-building programs codeml, baseml, basemlg,
codemlsites and yn00. See L<Bio::Tools::Phylo::PAML> or the PAML HOWTO
(http://bioperl.org/HOWTOs/html/PAML.html) for more information.

=head2 III.9.3 Map objects for manipulating genetic maps (Map::MapI, MapIO)

Bioperl map objects can be used to describe any type of biological map
data including genetic maps, STS maps etc.  Map I/O is performed with
the MapIO object which works in a similar manner to the SeqIO,
SearchIO and similar I/O objects described previously. In principle,
Map I/O with various map data formats can be performed.  However
currently only mapmaker format is supported.  Manipulation of
genetic map data with Bioperl Map objects might look like this:

  $mapio = new Bio::MapIO(-format => 'mapmaker', -file => $mapfile);
  $map = $mapio->next_map;  # get a map
  $maptype =  $map->type ;
  foreach $marker ( $map->each_element ) {
    $marker_name = $marker->name ;  # get the name of each map marker
  }

See L<Bio::MapIO> and L<Bio::Map::SimpleMap> for more information.

=head2 III.9.4 Bibliographic objects for querying bibliographic databases (Biblio)

Bio::Biblio objects are used to query bibliographic databases, such as MEDLINE.
The associated modules are built to work with OpenBQS-compatible databases
(see http://industry.ebi.ac.uk/openBQS). A Bio::Biblio object can execute 
a query like:

  my $collection = $biblio->find ('brazma', 'authors');
  while ( $collection->has_next ) {
      print $collection->get_next;
  }

See L<Bio::Biblio>, the scripts/biblio/biblio.PLS script, or the 
examples/biblio/biblio_examples.pl script for more information.


=for html <A NAME ="iii.9.5"></A>

=head2 III.9.5 Graphics objects for representing sequence objects as images (Graphics)

A user may want to represent sequence objects and their SeqFeatures graphically. 
The Bio::Graphics::* modules use Perl's GD.pm module to create a PNG or GIF image
given the SeqFeatures (Section L<"III.7.1">) contained within a Seq object.

These modules contain numerous methods to dictate the sizes, colors,
labels, and line formats within the image. For information see the
excellent Graphics-HOWTO (http://bioperl.org/HOWTOs/html/Graphics-HOWTO.html)
or in the docs/howto subdirectory. Additional documentation can be found in
L<Bio::Graphics>, L<Bio::Graphics::Panel>, and in the scripts in the
examples/biographics/ and scripts/graphics directories in the Bioperl package.

=head2 III.10 Bioperl alphabets

Bioperl modules use the standard extended single-letter genetic
alphabets to represent nucleotide and amino acid sequences.

In addition to the standard alphabet, the following symbols
are also acceptable in a biosequence:

 ?  (a missing nucleotide or amino acid)
 -  (gap in sequence)


=head2 III.10.1 Extended DNA / RNA alphabet

 (includes symbols for nucleotide ambiguity)
 ------------------------------------------
 Symbol       Meaning      Nucleic Acid
 ------------------------------------------
  A            A           Adenine
  C            C           Cytosine
  G            G           Guanine
  T            T           Thymine
  U            U           Uracil
  M          A or C
  R          A or G
  W          A or T
  S          C or G
  Y          C or T
  K          G or T
  V        A or C or G
  H        A or C or T
  D        A or G or T
  B        C or G or T
  X      G or A or T or C
  N      G or A or T or C


 IUPAC-IUB SYMBOLS FOR NUCLEOTIDE NOMENCLATURE:
   Cornish-Bowden (1985) Nucl. Acids Res. 13: 3021-3030.


=head2 III.10.2 Amino Acid alphabet

 ------------------------------------------
 Symbol   Meaning
 ------------------------------------------
 A        Alanine
 B        Aspartic Acid, Asparagine
 C        Cystine
 D        Aspartic Acid
 E        Glutamic Acid
 F        Phenylalanine
 G        Glycine
 H        Histidine
 I        Isoleucine
 K        Lysine
 L        Leucine
 M        Methionine
 N        Asparagine
 P        Proline
 Q        Glutamine
 R        Arginine
 S        Serine
 T        Threonine
 V        Valine
 W        Tryptophan
 X        Unknown
 Y        Tyrosine
 Z        Glutamic Acid, Glutamine
 *        Terminator

   IUPAC-IUP AMINO ACID SYMBOLS:
   Biochem J. 1984 Apr 15; 219(2): 345-373
   Eur J Biochem. 1993 Apr 1; 213(1): 2

=for html <A NAME ="IV."></A>

=head1 IV.  Auxiliary Bioperl Libraries (Bioperl-run, Bioperl-db, etc.)

=for html <A NAME ="iv.1"></A>

=head2 IV.1 Using the Bioperl Auxiliary Libraries

Beyond the bioperl "core" distribution which you get with the
"minimal" installation, bioperl contains numerous other modules in
so-called auxiliary libraries.  These auxiliary libraries include
bioperl-run, bioperl-db, bioperl-pipeline, bioperl-microarray and
bioperl-ext among others.  Generally, modules are placed in an
auxiliary library if either:

=over 2

=item *

The module requires the installation of additional non-standard
external programs or modules, or

=item *

The module is perceived to be of interest to only a small percentage
of the bioinformatics community

=back

However there are exceptions and it is not always obvious whether a
given module will be found in the "core" or in an auxiliary library.

At present, modules in the auxiliary packages can be obtained only by
means of the CVS system. To browse through the auxiliary libraries and
to obtain the download files, go to:

http://cvs.bioperl.org/cgi-bin/viewcvs/viewcvs.cgi/?cvsroot=bioperl

Install much like Bioperl:

  >perl Makefile.PL

and

  >make

Then:

  >make test

Once the auxiliary library has been installed in this manner, the
modules can be used in exactly the same manner as if they were in the
bioperl core.

=for html <A NAME ="iv.2"></A>

=head2 IV.2 Running programs (Bioperl-run, Bioperl-ext)

It possible to run various external (to Bioperl) sequence alignment
and sequence manipulation programs via a perl interface using bioperl.
However in most cases this requires having the bioperl-run auxiliary
library (some cases may require bioperl-ext). Prior to bioperl release
1.2, many of these features were available within the bioperl "core"
release.  However currently some of the required modules have been
transferred out of the core library. Some of the more commonly used of
these modules are described in this section.

=for html <A NAME ="iv.2.2"></A>

=head2 IV.2.1 Sequence manipulation using the Bioperl EMBOSS and PISE interfaces

EMBOSS (European Molecular Biology Open Source Software) is an extensive
collection of sequence analysis programs written in the C
programming language, from http://www.uk.embnet.org/Software/EMBOSS.
There are a number of algorithms in EMBOSS that are not found in "Bioperl
proper" (e.g. calculating DNA melting temperature, finding repeats,
identifying prospective antigenic sites) so if you cannot find
the function you want in bioperl you might be able to find it in EMBOSS.

EMBOSS programs are usually called from the command line but the
bioperl-run auxiliary library provides a Perl wrapper for EMBOSS
function calls so that they can be executed from within a Perl script.
Of course, the EMBOSS package as well as the bioperl-run must be
installed in order for the Bioperl wrapper to function.

In the future, it is planned that Bioperl EMBOSS objects will return
appropriate Bioperl objects to the calling script in addition to
generating standard EMBOSS reports.  This functionality is
being initially implemented with the EMBOSS sequence alignment
programs, so that they will return SimpleAlign objects in a manner
similar to the way the Bioperl-run modules TCoffee.pm and Clustalw.pm
work (see section L<"III.5"> for a discussion of SimpleAlign).

An example of the Bioperl EMBOSS wrapper where a file is returned
would be:

  $factory = new Bio::Factory::EMBOSS;
  $compseqapp = $factory->program('compseq');
  %input = ( -word     => 4,
	     -sequence => $seqObj,
	     -outfile  => $compseqoutfile );
  $compseqapp->run(\%input);
  $seqio = Bio::SeqIO->new( -file => $compseqoutfile ); # etc...

Note that a Seq object was used as input. The EMBOSS object can also
accept a file name as input, eg

  -sequence => "inputfasta.fa"

Some EMBOSS programs will return strings, others will create files
that can be read directly using Bio::SeqIO (section L<"III.2.1">), as
in the example above. It's worth mentioning that another way to
align sequences in bioperl is to run a program from the EMBOSS suite,
such as 'matcher'. This can produce an output file that bioperl can
read in using AlignIO:

  my $factory = new Bio::Factory::EMBOSS;
  my $prog = $factory->program('matcher');

  $prog->run({ -sequencea => Bio::Seq->new(-id => "seq1",
                                           -seq => $seqstr1),
               -sequenceb => Bio::Seq->new(-id => "seq2",
                                           -seq => $seqstr2),
               -aformat      => "pair",
               -alternatives => 2,
               -outfile'     => $outfile});

  my $alignio_fmt = "emboss";
  my $align_io = new Bio::AlignIO(-format => $alignio_fmt,
                                  -file   => $outfile);

The Pise interface is another way of extending Bioperl's sequence 
analysis capabilities. To use EMBOSS programs within Bioperl you need to
have EMBOSS locally installed, as well as  the bioperl-run library. 
In contrast, with Pise you only need to install bioperl-run, since the 
actual analysis programs reside at the Pise site. Advantages of Pise 
include not having to load additional programs locally and having access 
to an extraordinary variety of programs, including EMBOSS. However Pise has 
the disadvantages of lower performance and decreased security
since the data is transmitted over the net. Consider this example:

  my $genscan = Pise::genscan->new(
  "http://bioweb.pasteur.fr/cgi-bin/seqanal/genscan.pl",'letondal@pasteur.fr',
                                  seq => $seq,
                                  parameter_file => "Arabidopsis.smat");
  my $job = $genscan->run;
  my $parser = Bio::Tools::Genscan->new(-fh => $job->fh('genscan.out') );
  while(my $gene = $parser->next_prediction()) {
     my $prot = $gene->predicted_protein;
     print $prot->seq, "\n";
  }

Extremely simple! For more information on the Bioperl Pise interface see
http://www-alt.pasteur.fr/~letondal/Pise/ or the documentation in the
bioperl-run package.

=for html <A NAME ="iv.2.2"></A>

=head2 IV.2.2 Aligning 2 sequences with Blast using  bl2seq and AlignIO

As an alternative to Smith-Waterman, two sequences can also be aligned
in Bioperl using the bl2seq option of Blast within the StandAloneBlast
object.  To get an alignment - in the form of a SimpleAlign object -
using bl2seq, you need to parse the bl2seq report with the Bio::AlignIO
file format reader as follows:

  $factory = Bio::Tools::Run::StandAloneBlast->new('outfile' => 'bl2seq.out');
  $bl2seq_report = $factory->bl2seq($seq1, $seq2);
  # Use AlignIO.pm to create a SimpleAlign object from the bl2seq report
  $str = Bio::AlignIO->new(-file   => 'bl2seq.out',
                           -format => 'bl2seq');
  $aln = $str->next_aln();

=for html <A NAME ="iv.2.3"></A>

=head2 IV.2.3 Aligning multiple sequences (Clustalw.pm, TCoffee.pm)

For aligning multiple sequences (i.e. two or more), bioperl offers a
perl interface to the bioinformatics-standard clustalw and tcoffee
programs.  Clustalw has been a leading program in global multiple
sequence alignment (MSA) for several years.  TCoffee is a relatively
recent program - derived from clustalw - which has been shown to
produce better results for local MSA.

To use these capabilities, the clustalw and/or tcoffee programs
themselves need to be installed on the host system.  In addition, the
environmental variables CLUSTALDIR and TCOFFEEDIR need to be set to
the directories containg the executables.  See section L<"I.4"> and the
L<Bio::Tools::Run::Alignment::Clustalw> and
L<Bio::Tools::Run::Alignment::TCoffee> for information on downloading
and installing these programs.

From the user's perspective, the bioperl syntax for calling
Clustalw.pm or TCoffee.pm is almost identical.  The only differences
are the names of the modules themselves appearing in the initial "use"
and constructor statements and the names of the some of the individual
program options and parameters.

In either case, initially, a factory object must be created. The
factory may be passed most of the parameters or switches of the
relevant program.  In addition, alignment parameters can be changed
and/or examined after the factory has been created.  Any parameters
not explicitly set will remain as the underlying program's
defaults. Clustalw.pm/TCoffee.pm output is returned in the form of a
SimpleAlign object.  It should be noted that some Clustalw and TCoffee
parameters and features (such as those corresponding to tree
production) have not been implemented yet in the Perl interface.

Once the factory has been created and the appropriate parameters set,
one can call the method align() to align a set of unaligned sequences,
or profile_align() to add one or more sequences or a second alignment
to an initial alignment.  Input to align() consists of a set of
unaligned sequences in the form of the name of file containing the
sequences or a reference to an array of Seq objects. Typical
syntax is shown below. (We illustrate with Clustalw.pm, but the same
syntax - except for the module name - would work for TCoffee.pm)

  use Bio::Tools::Run::Alignment::Clustalw;
  @params = ('ktuple' => 2, 'matrix' => 'BLOSUM');
  $factory = Bio::Tools::Run::Alignment::Clustalw->new(@params);
  $ktuple = 3;
  $factory->ktuple($ktuple);  # change the parameter before executing
  $seq_array_ref = \@seq_array;
      # where @seq_array is an array of Bio::Seq objects
  $aln = $factory->align($seq_array_ref);

Clustalw.pm/TCoffee.pm can also align two (sub)alignments to each
other or add a sequence to a previously created alignment by using the
profile_align method. For further details on the required syntax and
options for the profile_align method, the user is referred to
L<Bio::Tools::Run::Alignment::Clustalw> and
L<Bio::Tools::Run::Alignment::TCoffee>. The user is also
encouraged to examine the script clustalw.pl in the examples/align 
directory.

=for html <A NAME ="iv.2.4"></A>

=head2    IV.2.4 Aligning 2 sequences with Smith-Waterman (pSW)

The Smith-Waterman (SW) algorithm is the standard method for producing
an optimal local alignment of two sequences.  Bioperl supports the
computation of SW alignments via the pSW object with the auxiliary
bioperl-ext library. Note that pSW only supports the alignment of
protein sequences, not nucleotide.

The SW algorithm itself is implemented in C and incorporated into
bioperl using an XS extension. This has significant efficiency
advantages but means that pSW will B<not> work unless you have
compiled the bioperl-ext auxiliary library.  If you have compiled the
bioperl-ext package, usage is simple, where the method align_and_show
displays the alignment while pairwise_alignment produces a (reference
to) a SimpleAlign object.

  use Bio::Tools::pSW;
  $factory = new Bio::Tools::pSW( '-matrix' => 'blosum62.bla',
  				  '-gap' => 12,
                                  '-ext' => 2, );
  $factory->align_and_show($seq1, $seq2, STDOUT);
  $aln = $factory->pairwise_alignment($seq1, $seq2);

SW matrix, gap and extension parameters can be adjusted as shown.
Bioperl comes standard with blosum62 and gonnet250 matrices.  Others
can be added by the user.  For additional information on accessing the
SW algorithm via pSW see the script psw.pl in the examples/tools
directory and the documentation in L<Bio::Tools::pSW>.

=for html <A NAME ="iv.3"></A>

=head2 IV.3 bioperl-db and BioSQL

The bioperl-db package is intended to enable the easy access and
manipulation of biology relational databases via a perl
interface. Obviously it requires having administrative access to a
relational database.  Currently the bioperl-db interface is
implemented to support databases in the Mysql, Postgres and Oracle formats.
More details on bioperl-db can be found in the bioperl-db CVS directory at
http://cvs.bioperl.org/cgi-bin/viewcvs/viewcvs.cgi/bioperl-db/?cvsroot=bioperl.

The database schema itself is not specified in the bioperl-db package but
in the BioSQL package, available at http://obda.open-bio.org/. It is worth 
mentioning that most of the bioperl objects mentioned above map directly to 
tables in the Biosql schema. Therefore object data such as sequences, their 
features, and annotations can be easily loaded into the databases, as in

  $loader->store($newid,$seqobj)

Similarly one can query the database in a variety of ways and retrieve
arrays of Seq objects. See biodatabases.pod,
L<Bio::DB::SQL::SeqAdaptor>, L<Bio::DB::SQL::QueryConstraint>, and
L<Bio::DB::SQL::BioQuery> for examples. The README file in the
bioperl-db package has a helpful overview of the approach used in
bioperl-db.

=for html <A NAME ="iv.4"></A>

=head2 IV.4 Other Bioperl auxiliary libraries

There a several other auxiliary libraries in the bioperl CVS
repository including bioperl-microarray, bioperl-pedigree, bioperl-gui,
bioperl-pipeline, bioperl-das-client and bioperl-corba-client. They
are typically for specialized uses and/or require multiple external
programs to run and/or are still pretty new and undeveloped. But if
you have a need for any of these capabailities, it is easy to take a
look at them at:
http://cvs.bioperl.org/cgi-bin/viewcvs/viewcvs.cgi/?cvsroot=bioperl
and see if they might be of use to you.

=for html <A NAME ="v.1"></A>

=head2 V.1 Appendix: Finding out which methods are used by which Bioperl Objects

At numerous places in the tutorial, the reader is directed to the
"documentation included with each of the modules."  As was mentioned in
the introduction, it is sometimes not easy in perl to determine the
appropriate documentation because objects inherit methods
from other objects (and the relevant documentation will be stored in the
object from which the method was inherited.)

For example, say you wanted to find documentation on the parse() method
of the module Genscan.pm.  You would not find this documentation in
the code for Genscan.pm, but rather in the code for AnalysisResult.pm
from which Genscan.pm inherits the parse method!

So how would you know to look in AnalysisResult.pm
for this documentation? The easy way is to use the special function
"option 100" in the bptutorial script. Specifically if you run:

 > perl -w bptutorial.pl 100 Bio::Tools::Genscan

you will receive the following output:

 ***Methods for Object Bio::Tools::Genscan ********

 Methods taken from package Bio::Root::IO
 catfile   close   gensym   new   qualify   qualify_to_ref
 rmtree   tempdir   tempfile   ungensym

 Methods taken from package Bio::Root::RootI
 DESTROY   stack_trace   stack_trace_dump   throw   verbose   warn

 Methods taken from package Bio::SeqAnalysisParserI
 carp   confess   croak   next_feature

 Methods taken from package Bio::Tools::AnalysisResult
 analysis_date   analysis_method   analysis_method_version   analysis_query   analysis_subject   parse

 Methods taken from package Bio::Tools::Genscan
 next_prediction

From this output, it is clear exactly from which object each method
of Genscan.pm is taken, and, in particular that parse() is
taken from the package Bio::Tools::AnalysisResult.

With this approach you can easily determine the source of any method
in any bioperl object.

=head2 V.2 Appendix: Tutorial demo scripts

The following scripts demonstrate many of the features of bioperl. To
run all the core demos, run:

 > perl -w  bptutorial.pl 0

To run a subset of the scripts do

 > perl -w  bptutorial.pl

and use the displayed help screen.

It may be best to start by just running one or two demos at a time. For 
example, to run the basic sequence manipulation demo, do:

 > perl -w  bptutorial.pl 1

Some of the later demos require that you have an internet connection
and/or that you have an auxiliary bioperl library and/or external
cpan module and/or external program installed.  They may also fail if
you are not running under Linux or Unix.  In all of these cases, the
script should fail gracefully simply saying the demo is being
skipped.  However if the script crashes, simply run the other demos
individually (and perhaps send an email to bioperl-l@bioperl.org
detailing the problem :-).

=cut

#!/usr/bin/perl

# PROGRAM  : bptutorial.pl
# PURPOSE  : Demonstrate various uses of the bioperl package
# AUTHOR   : Peter Schattner schattner@alum.mit.edu
# CREATED  : Dec 15 2000
# REVISION : $Id: bptutorial.pl,v 1.133 2003/12/16 02:57:24 bosborne Exp $

use strict;
use Bio::SimpleAlign;
use Bio::AlignIO;
use Bio::SeqIO;
use Bio::Seq;
my $outputfh = *STDOUT;

# subroutine references

my ($access_remote_db, $index_local_db, $fetch_local_db,
    $sequence_manipulations, $seqstats_and_seqwords,
    $restriction_and_sigcleave, $other_seq_utilities, $run_remoteblast,
    $run_standaloneblast,  $blast_parser, $bplite_parsing, $hmmer_parsing,
    $run_clustalw_tcoffee, $run_psw_bl2seq, $simplealign,
    $gene_prediction_parsing, $sequence_annotation, $largeseqs,
    $run_tree, $run_map, $run_struct, $run_perl, $searchio_parsing,
    $liveseqs, $demo_variations, $demo_xml, $display_help, $bpinspect1 );

# global variable file names.  Edit these if you want to try
#out a tutorial script on a different file

 Bio::Root::IO->catfile("t","data","ecolitst.fa");

my $dna_seq_file = Bio::Root::IO->catfile("t","data","dna1.fa");      # used in $sequence_manipulations
my $amino_seq_file = Bio::Root::IO->catfile("t","data","cysprot1.fa");  # used in $other_seq_utilities and in $run_perl
                                       #and $sequence_annotation
my $blast_report_file = Bio::Root::IO->catfile("t","data","blast.report");   # used in $blast_parser
my $bp_parse_file1 = Bio::Root::IO->catfile("t","data","blast.report");       # used in $bplite_parsing
my $bp_parse_file2 = Bio::Root::IO->catfile("t","data","psiblastreport.out"); # used in $bplite_parsing
my $bp_parse_file3 = Bio::Root::IO->catfile("t","data","bl2seq.out");        # used in $bplite_parsing
my $unaligned_amino_file = Bio::Root::IO->catfile("t","data","cysprot1a.fa"); # used in $run_clustalw_tcoffee
my $aligned_amino_file = Bio::Root::IO->catfile("t","data","testaln.pfam");    # used in $simplealign

# other global variables
my (@runlist, $n );


##############################
#  display_help
$display_help = sub {


# Prints usage information for tutorial script.

    print STDERR <<"QQ_PARAMS_QQ";

The following numeric arguments can be passed to run the corresponding demo-script.
1  => sequence_manipulations 
2  => seqstats_and_seqwords 
3  => restriction_and_sigcleave 
4  => other_seq_utilities 
5  => run_perl
6  => searchio_parsing 
7  => bplite_parsing 
8  => hmmer_parsing 
9  => simplealign 
10 => gene_prediction_parsing 
11 => access_remote_db 
12 => index_local_db 
13 => fetch_local_db    (NOTE: needs to be run with demo 12)
14 => sequence_annotation 
15 => largeseqs 
16 => liveseqs 
17 => run_struct
18 => demo_variations 
19 => demo_xml 
20 => run_tree 
21 => run_map
22 => run_remoteblast 
23 => run_standaloneblast 
24 => run_clustalw_tcoffee 
25 => run_psw_bl2seq 

In addition the argument "100" followed by the name of a single
bioperl object will display a list of all the public methods
available from that object and from what object they are inherited.

Using the parameter "0" will run all the tests that do not require 
external programs (i.e. tests 1 to 22). 
Using any other argument (or no argument) will run this display.

So typical command lines might be:
To run all core demo scripts:
 > perl -w  bptutorial.pl 0
or to just run the local indexing demos:
 > perl -w  bptutorial.pl 12 13
or to list all the methods available for object Bio::Tools::SeqStats -
 > perl -w  bptutorial.pl 100 Bio::Tools::SeqStats

QQ_PARAMS_QQ

exit(0);
};


## Note: "main" routine is at very end of script

#################################################
#   access_remote_db():
#

$access_remote_db = sub {
    eval { 
	require Bio::DB::GenBank;
    };
    if($@ ) {
	warn "LWP::UserAgent or HTTP::Request or IO::String doesn't appear to be loaded, cannot run the access_remote_db method";
	return 0;
    }
    print $outputfh "Beginning remote database access example... \n";

    # III.2.1 Accessing remote databases (Bio::DB::GenBank, etc)

    my ($gb, $seq1, $seq2, $seq1_id, $seqobj, $seq2_id,$seqio);

    eval {
        $gb = new Bio::DB::GenBank();
        $seq1 = $gb->get_Seq_by_id('MUSIGHBA1');
    };

if ($@ || !$seq1) {
    warn "Warning: Couldn't connect to Genbank with Bio::DB::GenBank.pm!\nProbably no network access.\nSkipping method 'access_remote_db'.\n";
    return 0;
}
    $seq1_id =  $seq1->display_id();
    print $outputfh "seq1 display id is $seq1_id \n";
    $seq2 = $gb->get_Seq_by_acc('AF303112');
    $seq2_id =  $seq2->display_id();
    print $outputfh "seq2 display id is $seq2_id \n";
    $seqio = $gb->get_Stream_by_id([ qw(2981014 J00522 AF303112)]);
    $seqobj = $seqio->next_seq();
    print $outputfh "Display id of first sequence in stream is ", $seqobj->display_id()  ,"\n";
    return 1;
} ;


#################################################
#  index_local_db ():
#

$index_local_db = sub {

    use Bio::Index::Fasta; # using fasta file format
    use strict; # some users have reported that this is required

    my ( $Index_File_Name, $inx1, $inx2, $id, $dir, $key,
         $keyfound, $seq, $indexhash);
    print $outputfh "\nBeginning indexing local_db example... \n";
    print $outputfh "This subroutine unlikely to run unless OS = unix\n";


    # III.2.2 Indexing and accessing local databases
    # (Bio::Index::*,  bp_index.pl,  bp_fetch.pl)

    # first create the index
    $Index_File_Name = 'bptutorial.indx';

    eval { use Cwd; $dir = cwd; };
    # CWD not installed, revert to unix behavior, best we can do
    if( $@) { $dir = `pwd`;}
    $inx1 = Bio::Index::Fasta->new
        ('-FILENAME' => "$dir/$Index_File_Name",
         '-write_flag' => 1);

    $inx1->make_index(Bio::Root::IO->catfile("$dir","t","data","multifa.seq") );
    $inx1->make_index(Bio::Root::IO->catfile("$dir","t","data","seqs.fas") );


#    $inx1->make_index("$dir/t/data/multifa.seq");
#    $inx1->make_index("$dir/t/data/seqs.fas");
    print $outputfh "Finished indexing local_db example... \n";

    return 1;
} ;


#################################################
#  fetch_local_db ():
#

$fetch_local_db = sub {

    use Bio::Index::Fasta; # using fasta file format
    use strict; # some users have reported that this is required

    my ( $Index_File_Name, $inx2, $id, $dir, $key,
         $keyfound, $seq, $indexhash,$value );
    print $outputfh "\nBeginning retrieving local_db example... \n";

    # then retrieve some files
    #$Index_File_Name = shift;
    $Index_File_Name = 'bptutorial.indx';

    eval { use Cwd; $dir = cwd; };
    # CWD not installed, revert to unix behavior, best we can do
    if( $@) { $dir = `pwd`;}

    eval {$inx2 = Bio::Index::Abstract->new
	      ('-FILENAME'  => Bio::Root::IO->catfile("$dir","$Index_File_Name") ); };
   if( $@ ) {
      print STDERR "Cannot find local index file $Index_File_Name\n";
      print STDERR "Perhaps you didn't run the index_local_db demo? \n";
      print STDERR "Skipping fetch_local_db example.\n\n";
      return 0;
    }

    $indexhash = $inx2->db();
    $keyfound = "";
    while ( ($key,$value) = each %$indexhash ) {
        if ( $key =~ /97/ ) { $keyfound = 'true'; $id = $key; last; }
    }
    if ($keyfound) {
        $seq = $inx2->fetch($id);
        print $outputfh "Sequence ", $seq->display_id(),
        " has length  ", $seq->length()," \n";
    }

    unlink "$dir/$Index_File_Name" ;

    return 1;
} ;



#################################################
# sequence_manipulations  ():
#

$sequence_manipulations = sub {

    my ($infile, $in, $out, $seqobj);
    $infile = $dna_seq_file;

    print $outputfh "\nBeginning sequence_manipulations and SeqIO example... \n";
    # III.3.1 Transforming sequence files (SeqIO)

    $in  = Bio::SeqIO->new('-file' => $infile ,
                           '-format' => 'Fasta');
    $seqobj = $in->next_seq();

    # perl "tied filehandle" syntax is available to SeqIO,
    # allowing you to use the standard <> and print operations
    # to read and write sequence objects, eg:
    #$out = Bio::SeqIO->newFh('-format' => 'EMBL');

    $out = Bio::SeqIO->newFh('-format'   => 'fasta',
			     '-noclose'  => 1,
			     '-fh'       => $outputfh);

    print $outputfh "First sequence in fasta format... \n";
    print $out $seqobj;

    # III.4 Manipulating individual sequences

    # The following methods return strings


    print $outputfh "Seq object display id is ",
    $seqobj->display_id(), "\n"; # the human read-able id of the sequence
    print $outputfh "Sequence is ",
    $seqobj->seq()," \n";        # string of sequence
    print $outputfh "Sequence from 5 to 10 is ",
    $seqobj->subseq(5,10)," \n"; # part of the sequence as a string
    print $outputfh "Acc num is ",
    $seqobj->accession_number(), " \n"; # when there, the accession number
    print $outputfh "Alphabet is ",
    $seqobj->alphabet(), " \n";    # one of 'dna','rna','protein'
    print $outputfh "Primary id is ", $seqobj->primary_seq->primary_id()," \n";
    # a unique id for this sequence irregardless
    #print $outputfh "Primary id is ", $seqobj->primary_id(), " \n";
    # a unique id for this sequence irregardless
    # of its display_id or accession number

    # The following methods return an array of  Bio::SeqFeature objects
    $seqobj->top_SeqFeatures; # The 'top level' sequence features
    $seqobj->all_SeqFeatures; # All sequence features, including sub
    # seq features

    # The following methods returns new sequence objects,
    # but do not transfer features across
    # truncation from 5 to 10 as new object
    print $outputfh "Truncated Seq object sequence is ",
    $seqobj->trunc(5,10)->seq(), " \n";
    # reverse complements sequence
    print $outputfh "Reverse complemented sequence 5 to 10  is ",
    $seqobj->trunc(5,10)->revcom->seq, "  \n";
    # translation of the sequence
    print $outputfh "Translated sequence 6 to 15 is ",
    $seqobj->translate->subseq(6,15), " \n";


    my $c = shift;
    $c ||= 'ctgagaaaataa';

    print $outputfh "\nBeginning 3-frame and alternate codon translation example... \n";

    my $seq = new Bio::PrimarySeq(-seq => $c,
                                  -id => 'no.One');
    print $outputfh "$c translated using method defaults   : ",
    $seq->translate->seq, "\n";

    # Bio::Seq uses same sequence methods as PrimarySeq
    my $seq2 = new Bio::Seq('-SEQ' => $c, '-ID' => 'no.Two');
    print $outputfh "$c translated as a coding region (CDS): ",
    $seq2->translate(undef, undef, undef, undef, 1)->seq, "\n";

    print $outputfh "\nTranslating in all six frames:\n";
    my @frames = (0, 1, 2);
    foreach my $frame (@frames) {
        print $outputfh  " frame: ", $frame, " forward: ",
        $seq->translate(undef, undef, $frame)->seq, "\n";
        print $outputfh  " frame: ", $frame, " reverse-complement: ",
        $seq->revcom->translate(undef, undef, $frame)->seq, "\n";
    }

    print $outputfh "Translating with all codon tables using method defaults:\n";
    my @codontables = qw( 1 2 3 4 5 6 9 10 11 12 13 14 15 16 21 );
    foreach my $ct (@codontables) {
        print $outputfh $ct, " : ",
        $seq->translate(undef, undef, undef, $ct)->seq, "\n";
    }

    return 1;
} ;

#################################################                                      ;
#  seqstats_and_seqwords ():
#

$seqstats_and_seqwords = sub {

    use Bio::Tools::SeqStats;
    use Bio::Tools::SeqWords;

    print $outputfh "\nBeginning seqstats_and_seqwords example... \n";


    my ($seqobj, $weight, $monomer_ref, $codon_ref,
        $seq_stats, $words, $hash);
    $seqobj = Bio::Seq->new
        (-seq =>'ACTGTGGCGTCAACTGACTGTGGCGTCAACTGACTGTGGGCGTCAACTGACTGTGGCGTCAACTG',
         -alphabet =>'dna',
         -id =>'test');


    # III.4.1 Obtaining basic sequence statistics- MW,
    # residue &codon frequencies(SeqStats, SeqWord)


    $seq_stats  =  Bio::Tools::SeqStats->new($seqobj);
    $weight = $seq_stats->get_mol_wt();
    $monomer_ref = $seq_stats->count_monomers();
    $codon_ref = $seq_stats->count_codons();  # for nucleic acid sequence
    print $outputfh "Sequence \'test\' is ", $seqobj->seq(), " \n";
    print $outputfh "Sequence ", $seqobj->id()," molecular weight is $$weight[0] \n";
    # Note, $weight is an array reference
    print $outputfh "Number of A\'s in sequence is $$monomer_ref{'A'} \n";
    print $outputfh "Number of ACT codon\'s in sequence is $$codon_ref{'ACT'} \n";

    $words = Bio::Tools::SeqWords->new($seqobj);
    $hash = $words->count_words(6);
    print $outputfh "Number of 6-letter \'words\' of type ACTGTG in",
    " sequence is $$hash{'ACTGTG'} \n";

    return 1;
    } ;


#################################################
# restriction_and_sigcleave  ():
#

$restriction_and_sigcleave = sub {
    require Bio::Restriction::EnzymeCollection;
    require Bio::Restriction::Analysis;
    require Bio::Tools::Sigcleave;

    my ($re1, $re2, $allcutters, $rarecutters, @fragments1,
        @fragments2, $analysis, $seqobj, $dna);
    print $outputfh "\nBeginning restriction enzyme example... \n";

    # III.4.4 Identifying restriction enzyme sites (Bio::Restriction)

    $dna = 'CCTCCGGGGACTGCCGTGCCGGGCGGGAATTCGCCATGGCGACCCTGGAAAAGCTGATATCGAAGGCCTTCGA';

    # Build sequence and restriction enzyme objects.
    $seqobj = new Bio::Seq(-id  => 'test_seq',
                           -seq => $dna);

    # a numer of methods exist to create custom enzyme lists
    $allcutters  = new Bio::Restriction::EnzymeCollection;
    $rarecutters = $allcutters->cutters(-start => 6, -end => 8);

    # this analysis object knows only of rare cutters
    $analysis = Bio::Restriction::Analysis->new(-seq => $seqobj,
                                                -enzymes => $rarecutters);
    my @rarecutters = $rarecutters->available_list;

    print $outputfh "The following ".  scalar @rarecutters.
        " rarely cutting enzymes are available\n";
    print $outputfh join(" ",@rarecutters),"\n";

    $re1 = 'EcoRI';
    @fragments1 = $analysis->fragments($re1);
    # $re1 is the enzyme cutting the DNA in $seqobj

    print $outputfh "\nThe sequence of " . $seqobj->display_id . " is " .
    $seqobj->seq . "\n";
    print $outputfh "When cutting " . $seqobj->display_id() . " with " .
    $re1 . " the initial fragment out of ". scalar @fragments1. " is\n" . $fragments1[0];

    $re2 = 'EcoRV';
    @fragments2 = $analysis->fragments($re2);

    print $outputfh "\nWhen cutting ", $seqobj->display_id(),
    " with ", $re2;
    print $outputfh " the second fragment out of ". scalar @fragments2. " is\n", $fragments2[1], " \n";

    # III.4.7 Identifying amino acid cleavage sites (Sigcleave)

    print $outputfh "\nBeginning  signal cleaving site location example... \n";

    my ( $sigcleave_object, %raw_results , $location,
         $formatted_output, $protein, $in, $seqobj2);

    $protein = 
"MKVILLFVLAVFTVFVSSRGIPPEEQSQFLEFQDKFNKKYSHEEYLERFEIFKSNLGKIEELNLIAINHKADTKFGVNKFADLSSDEFKNYYLNNKEAIFTDDLPVADYLDDEFINSIPTAFDWRTRGAVTPVKNQGQCGSCWSFSTTGNVEGQHFISQNKLVSLSEQNLVDCDHECMEYEGEEACDEGCNGGLQPNAYNYIIKNGGIQTESSYPYTAETGTQCNFNSANIGAKISNFTMIPKNETVMAGYIVSTGPLAIAADAVEWQFYIGGVFDIPCNPNSLDHGILIVGYSAKNTIFRKNMPYWIVKNSWGADWGEQGYIYLRRGKNTCGVSNFVSTSII";
    $formatted_output = "";

    # Build object
    # Note that Sigcleave is passed a raw sequence
    # rather than a sequence object when it is created.
    $sigcleave_object = new Bio::Tools::Sigcleave
        ('-id' => 'test_sigcleave_seq',
         '-type' => 'amino',
         '-threshold' => 3.0,
         '-seq' => $protein);

    %raw_results      = $sigcleave_object->signals;
    $formatted_output = $sigcleave_object->pretty_print;

    print $outputfh " SigCleave \'raw results\': \n";
    foreach $location (sort keys %raw_results) {
        print $outputfh " Cleave site found at location $location ",
        "with value of $raw_results{$location} \n";
    }
    print $outputfh "\nSigCleave formatted output: \n $formatted_output \n";
    return 1;
} ;


#################################################
#  run_standaloneblast ():
#

$run_standaloneblast = sub {
    eval {require Bio::Tools::Run::StandAloneBlast; };
    if ( $@ ) {
      print STDERR "Cannot find Bio::Tools::Run::StandAloneBlast\n";
      print STDERR "You will need the bioperl-run library to run StandAlnoeBlast\n";
      print STDERR "Skipping local blast example:\n";
      return 0;
    }
    print $outputfh "\nBeginning run_standaloneblast example... \n";
    my (@params, $factory, $input, $blast_report, $blast_present,
        $database, $sbjct, $str, $seq1);

#    $database = $_[0] || 'ecoli.nt'; # user can select local nt database
    $database = $_[0] || defined $ENV{BLASTDB} ? "$ENV{BLASTDB}/ecoli.nt" : 
	"$ENV{BLASTDIR}/data/ecoli.nt"; # user can select local nt database
    #@params = ('program' => 'blastn', 'database' => 'ecoli.nt');
    @params = ('program' => 'blastn', 'database' => $database);
    $factory = Bio::Tools::Run::StandAloneBlast->new(@params);

    unless ($factory->executable('blastall')) {
        warn "blastall program not found. Skipping StandAloneBlast example\n";
        return 0;
    }

    $str = Bio::SeqIO->new('-file'=> 
			   Bio::Root::IO->catfile("t","data","dna2.fa") ,
#    $str = Bio::SeqIO->new('-file'=>'t/data/dna2.fa' ,
                           '-format' => 'fasta', );
    $seq1 = $str->next_seq();

    $blast_report = $factory->blastall($seq1);
    my $result = $blast_report->next_result; 
    $sbjct = $result->next_hit;

    print $outputfh " Hit name is ", $sbjct->name, " \n";

    return 1;
} ;

#################################################
#  run_remoteblast ():
#

$run_remoteblast = sub {
    print $outputfh "\nBeginning run_remoteblast example... \n";
    eval { require Bio::Tools::Run::RemoteBlast; };

    if ( $@ ) {
      print STDERR "Cannot find Bio::Tools::Run::RemoteBlast\n";
      print STDERR "Skipping run_remoteblast example:\n";
    } else {
      my (@params, $remote_blast_object, $blast_file, $r, $rc,
         $database);

      $database =  'ecoli';
      @params = ('-prog'   => 'blastp', 
                 '-data'   => $database,
                 '-expect' => '1e-10',
                 '-readmethod' => 'BPlite' );

      $remote_blast_object = Bio::Tools::Run::RemoteBlast->new(@params);
      $blast_file = Bio::Root::IO->catfile("t","data","ecolitst.fa");
      eval {
	  $r = $remote_blast_object->submit_blast( $blast_file);
      };
      if (($r < 0) || $@)  {
	  warn "\n\n**Warning**: Couldn't connect to NCBI with Bio::Tools::Run::StandAloneBlast.pm!\nProbably no network access.\nSkipping Test\n";
	  return 0;
      }
      print $outputfh "submitted Blast job\n";
      while ( my @rids = $remote_blast_object->each_rid ) {
	  foreach my $rid ( @rids ) {
	      $rc = $remote_blast_object->retrieve_blast($rid);
	      print $outputfh "retrieving results...\n";
	      if( !ref($rc) ) {   # $rc not a reference => either error 
		  # or job not yet finished
		  if( $rc < 0 ) {
		      $remote_blast_object->remove_rid($rid);
		      print $outputfh "Error return code for BlastID code $rid ... \n";
		  }
		  sleep 5;
	      } else {
            $remote_blast_object->remove_rid($rid);
            while ( my $sbjct = $rc->nextSbjct ) {
              print $outputfh "sbjct name is ", $sbjct->name, "\n";
              while ( my $hsp = $sbjct->nextHSP ) {
                print $outputfh "score is ", $hsp->score, "\n"; 
              }
            }
          }
        }
      }
    }
  return 1;
} ;


#################################################
#  searchio_parsing ():
#

$searchio_parsing = sub {

my ($searchio, $result,$hit,$hsp);

use lib '.';
use Bio::SearchIO;
use Bio::Root::IO;

print $outputfh "\nBeginning searchio-parser example... \n";
$searchio = new Bio::SearchIO ('-format' => 'blast',
  '-file' => Bio::Root::IO->catfile('t','data','ecolitst.bls'));

$result = $searchio->next_result;

print $outputfh "Database name is ", $result->database_name , "\n";
print $outputfh "Algorithm is ", $result->algorithm , "\n";
print $outputfh "Query length used is ", $result->query_length , "\n";
print $outputfh "Kappa value is ", $result->get_statistic('kappa') , "\n";
print $outputfh "Name of matrix used is ", $result->get_parameter('matrix') , "\n";

$hit = $result->next_hit;
print $outputfh "First hit name is ", $hit->name , "\n";
print $outputfh "First hit length is ", $hit->length , "\n";
print $outputfh "First hit accession number is ", $hit->accession , "\n";

$hsp = $hit->next_hsp;
print $outputfh "First hsp query start is ", $hsp->query->start , "\n";
print $outputfh "First hsp query end is ", $hsp->query->end , "\n";
print $outputfh "First hsp hit start is ", $hsp->hit->start , "\n";
print $outputfh "First hsp hit end is ", $hsp->hit->end , "\n";

    return 1;
} ;


#################################################
#  bplite_parsing ():
#

$bplite_parsing = sub {

    use Bio::Tools::BPlite;
    my ($file1, $file2, $file3, $report,$report2 , $report3 ,
        $last_iteration, $sbjct,  $total_iterations, $hsp,
        $matches, $loop);

    print $outputfh "\nBeginning bplite, bppsilite, bpbl2seq parsing example... \n";
    ($file1, $file2, $file3) = ($bp_parse_file1,
                                $bp_parse_file2 ,$bp_parse_file3 );
    $report = Bio::Tools::BPlite->new('-file'=>$file1);
    $sbjct = $report->nextSbjct;

    print $outputfh " Hit name is ", $sbjct->name, " \n";
    while ($hsp = $sbjct->nextHSP) {
        $hsp->score;
    }

    use Bio::Tools::BPpsilite;
    $report2 = Bio::Tools::BPpsilite->new('-file'=>$file2);
    $total_iterations = $report2->number_of_iterations;
    $last_iteration = $report2->round($total_iterations);

    # print first 10 psiblast hits
    for ($loop = 1; $loop <= 10; $loop++) {
        $sbjct =  $last_iteration->nextSbjct;
        $sbjct && print $outputfh " PSIBLAST Hit is ", $sbjct->name, " \n";
    }

    #
    use Bio::Tools::BPbl2seq;
    $report3 = Bio::Tools::BPbl2seq->new('-file'  => $file3,
                                         '-report_type' => 'BLASTP',
					 '-queryname' => "ALEU_HORVU");
    $hsp = $report3->next_feature;
    $matches = $hsp->match;
    print $outputfh " Number of Blast2seq matches for first hsp equals $matches \n";
    #

    return 1;
} ;


#################################################
#  hmmer_parsing ():
#

$hmmer_parsing = sub {

    print $outputfh "\nBeginning hmmer_parsing example \n" .
          " (note: this test may be a little slow, please be patient...) \n";
    # Parsing HMM reports
    use Bio::SearchIO;

    my $in = new Bio::SearchIO('-format' => 'hmmer',
          '-file' => Bio::Root::IO->catfile("t","data","hmmsearch.out"));
    my $res = $in->next_result;
    # get a Bio::Search::Result::HMMERResult object
    print $outputfh "The first result query name is ", $res->query_name,  "\n";
    print $outputfh "The first result HMM name is ",  $res->hmm_name, "\n";
    my $first_hit = $res->next_hit;
    print $outputfh "The name of the first hit is ", $first_hit->name, "\n";
    my $hsp = $first_hit->next_hsp;
    print $outputfh "The score of the first hsp of the first hit is ", $hsp->score, "\n";
    return 1;
} ;

#################################################
# run_clustalw_tcoffee  ():
#

$run_clustalw_tcoffee = sub {

#    use Bio::Tools::Run::Alignment::TCoffee;
#    use Bio::Tools::Run::Alignment::Clustalw;
    my (@params, $factory, $ktuple, $aln, $seq_array_ref, $strout);
    my (@seq_array, $seq, $str, $infile);

    $infile = $unaligned_amino_file;

    # Aligning multiple sequences (Clustalw.pm, TCoffee.pm)
    print $outputfh "\nBeginning run_clustalw example... \n";
    eval {require Bio::Tools::Run::Alignment::Clustalw; };
    if ( $@ ) { 
	print STDERR "Cannot find Bio::Tools::Run::Alignment::Clustalw\n";
        print STDERR "You will need the bioperl-run library to run clustalw with bioperl\n";
	print STDERR "Skipping local clustalw demo:\n";
    } else {

	# put unaligned sequences in a Bio::Seq array
	$str = Bio::SeqIO->new('-file'=> $infile,
			       '-format' => 'fasta');
	@seq_array =();
	while ($seq = $str->next_seq() ) { push (@seq_array, $seq) ;}
	$seq_array_ref = \@seq_array;
	# where @seq_array is an array of Bio::Seq objects
	@params = ('ktuple' => 2, 'matrix' => 'BLOSUM', 'quiet' => 1);
	$factory = Bio::Tools::Run::Alignment::Clustalw->new(@params);
	unless( !$factory->executable ) {
	    $ktuple = 3;
	    $factory->ktuple($ktuple);  # change the parameter before executing
	    $aln = $factory->align($seq_array_ref);
	    $strout = Bio::AlignIO->newFh('-format' => 'msf',
					  '-noclose'=> 1,
					  '-fh'     => $outputfh);
	    print $outputfh "Output of clustalw alignment... \n";
	    print $strout $aln;
	} else {
	    warn "Clustalw program not found. Skipping run_clustalw example....\n";
	}
    }
    print $outputfh "\nBeginning run_tcoffee example... \n";

    eval {require Bio::Tools::Run::Alignment::TCoffee; };
    if ( $@ ) { 
	print STDERR "Cannot find Bio::Tools::Run::Alignment::TCoffee\n";
        print STDERR "You will need the bioperl-run library to run TCoffee with bioperl\n"; 
        print STDERR "Skipping local TCoffee demo:\n";
	return 0;
    }
    @params = ('ktuple' => 2, 'matrix' => 'BLOSUM', 'quiet' => 1);
    $factory = Bio::Tools::Run::Alignment::TCoffee->new(@params);
    unless( !$factory->executable ) {
	$ktuple = 3;
        $factory->ktuple($ktuple);  # change the parameter before executing
        $aln = $factory->align($seq_array_ref);
        $strout = Bio::AlignIO->newFh('-format' => 'msf',
				      '-noclose'=> 1,
				      '-fh'     => $outputfh);
        print $outputfh "Output of TCoffee alignment... \n";
        print $strout $aln;
    } else {
        warn "TCoffee program not found. Skipping run_TCoffee example....\n";
    }
    return 1;
} ;

#################################################
# simplealign  ():
#

$simplealign = sub {

    my ($in, $out1,$out2, $aln, $threshold_percent, $infile);
    my ( $str, $resSlice1, $resSlice2, $resSlice3, $tmpfile);

    print $outputfh "\nBeginning simplealign and alignio example... \n";
    # III.3.2 Transforming alignment files (AlignIO)
    $infile = $aligned_amino_file;
    #$tmpfile = "test.tmp";
    $in  = Bio::AlignIO->new('-file' => $infile ,
                             '-format' => 'pfam');
    $out1 = Bio::AlignIO->newFh('-format' => 'msf',
				'-noclose'=> 1,
				'-fh'     => $outputfh);

    # while ( my $aln = $in->next_aln() ) { $out->write_aln($aln);  }
    $aln = $in->next_aln() ;
    print $outputfh "Alignment to display in msf format... \n";
    print $out1 $aln;

    $threshold_percent = 60;
    $str = $aln->consensus_string($threshold_percent) ;
    print $outputfh "Consensus string with threshold = $threshold_percent is $str\n";

    print $outputfh "The average percentage identity of the alignment is ", $aln->percentage_identity. "\n";

    my $seqname = '1433_LYCES';
    my $residue_number = 14;
    my $pos = $aln->column_from_residue_number($seqname, $residue_number);
    print $outputfh "Residue number $residue_number of the sequence $seqname in the alignment occurs at column $pos. \n";

    my $s1 = new Bio::LocatableSeq (-id => 'AAA',  -seq => 'aawtat-tn-', -start => 1, -end => 8,
                            -alphabet => 'dna' );
    my $s2 = new Bio::LocatableSeq (-id => 'BBB',  -seq => '-aaaat-tt-', -start => 1,
                            -end => 7,  -alphabet => 'dna');
    my $a = new Bio::SimpleAlign;
    $a->add_seq($s1);
    $a->add_seq($s2);

    print $outputfh "The first sequence in the dna alignment is... \t", $s1->seq , "\n";
    print $outputfh "The second sequence in the dna alignment is... \t", $s2->seq , "\n";
    my $iupac_consensus =  $a->consensus_iupac;
    print $outputfh "The IUPAC consensus of the dna alignment is... \t",$iupac_consensus  , "\n";

    return 1;
} ;

#################################################
# run_psw_bl2seq  ():
#

$run_psw_bl2seq = sub {

    #use Bio::Tools::pSW;
    #use Bio::Tools::Run::StandAloneBlast;
    my ($factory, $aln, $out1, $out2, $str, $seq1, $seq2, @params);
    print $outputfh "\nBeginning run_psw_bl2seq example... \n";
    eval { require Bio::Tools::pSW; };
    if( $@ ) {
        print STDERR "\nThe C-compiled engine for Smith Waterman alignments (Bio::Ext::Align) has not been installed.\n";
        print STDERR "Please read the install the bioperl-ext package\n";
	print STDERR "Skipping Smith-Waterman demo:\n";
    } else {

	# Aligning 2 sequences with Smith-Waterman (pSW)

	# Get protein sequences from file
        $str = Bio::SeqIO->new('-file'=>Bio::Root::IO->catfile("t","data","amino.fa") ,
			       '-format' => 'Fasta', );
	$seq1 = $str->next_seq();
	$seq2 = $str->next_seq();

	$factory = new Bio::Tools::pSW( '-matrix' => 'scripts/tools/blosum62.bla',
					'-gap' => 12,
					'-ext' => 2, );

	$factory->align_and_show($seq1,$seq2,$outputfh);
	$aln = $factory->pairwise_alignment($seq1,$seq2);

	$out1 = Bio::AlignIO->newFh('-format' => 'fasta',
				    '-noclose'=> 1,
				    '-fh'     => $outputfh);
	print $outputfh "The Smith-Waterman alignment in fasta format... \n";
	print $out1 $aln;
    }

    # Aligning 2 sequences with Blast using  bl2seq and AlignIO

    # Bl2seq testing
    # first create factory for bl2seq

    eval { require Bio::Tools::Run::StandAloneBlast; };
    if ( $@ ){
	print STDERR "Cannot find Bio::Tools::Run::StandAloneBlast module\n";
	print STDERR "You will need the bioperl-run library to run bl2seq\n";
	print STDERR "Skipping bl2seq demo:\n";
	return 0;
    }

    @params = ('outfile' => 'bl2seq.out');
    $factory = Bio::Tools::Run::StandAloneBlast->new(@params);

    unless ($factory->executable('bl2seq') ) {
        warn "\n Blast program not found. Skipping bl2seq example\n\n";
        return 0;
    }
    $factory->bl2seq($seq1, $seq2);

    # Use AlignIO.pm to create a SimpleAlign object from the bl2seq report
    $str = Bio::AlignIO->new('-file'=> 'bl2seq.out',
                             '-format' => 'bl2seq');
    $aln = $str->next_aln();

    $out2 = Bio::AlignIO->newFh('-format' => 'fasta',
				'-noclose'=> 1,
				'-fh'     => $outputfh);
    print $outputfh "The Blast 2 sequence alignment in fasta format... \n";
    print $out2 $aln;

    return 1;
} ;


#################################################
#  gene_prediction_parsing ():
#

$gene_prediction_parsing = sub {

    use Bio::Tools::Genscan;

    print $outputfh "\nBeginning genscan_result_parsing example... \n";
    my ($genscan, $gene, @exon_arr, $first_exon);

    # III.7 Searching for genes and other structures
    # on genomic DNA (Genscan, ESTScan, MZEF)

    use Bio::Tools::Genscan;

    $genscan = Bio::Tools::Genscan->new('-file' => Bio::Root::IO->catfile("t","data","genomic-seq.genscan"));
    # $gene is an instance of Bio::Tools::Prediction::Gene
    # $gene->exons() returns an array of Bio::Tools::Prediction::Exon objects
    while($gene = $genscan->next_prediction()) {
        print $outputfh "Protein corresponding to current gene prediction is ",
        $gene->predicted_protein->seq()," \n";
        @exon_arr = $gene->exons();
        $first_exon = $exon_arr[0];
        print $outputfh "Start location of first exon of current predicted gene is ",
        $first_exon->start," \n";
    }
    $genscan->close();

    use Bio::Tools::Sim4::Results;
    print $outputfh "\nBeginning Sim4_result_parsing example... \n";
    my ($sim4,$exonset, @exons, $exon, $homol);

   $sim4 = new Bio::Tools::Sim4::Results(-file=>  Bio::Root::IO->catfile("t","data","sim4.rev"), -estisfirst=>0);
   $exonset = $sim4->next_exonset;
   @exons = $exonset->sub_SeqFeature();
   $exon = $exons[1];
    print $outputfh "Start location of first exon of first exon set is ",$exon->start(), " \n";
   print $outputfh "Name of est sequence is ",$exon->est_hit()->seq_id(), " \n";
   print $outputfh "The length of the est hit is ",$exon->est_hit()->seqlength(), " \n";
   $sim4->close();

    return 1;
} ;


#################################################
#  sequence_annotation ():
#

$sequence_annotation = sub {

    print $outputfh "\nBeginning sequence_annotation example... \n";
    my ($feat, $feature1, $feature2,$seqobj, @topfeatures, @allfeatures,
        $ann, $in, $infile, $other, $answer);
    # III.7.1 Representing sequence annotations (SeqFeature)

    $infile = $amino_seq_file;

    $in  = Bio::SeqIO->new('-file' => $infile ,
                           '-format' => 'Fasta');
    $seqobj = $in->next_seq();

    $feature1 = new Bio::SeqFeature::Generic
        ('-start' => 10,
         '-end' => 40,
         '-strand' => 1,
         '-primary' => 'exon',
         '-source'  => 'internal', );

    $feature2 = new Bio::SeqFeature::Generic
        ( '-start' => 20,
          '-end' => 30,
          '-strand' => 1,
          '-primary' => 'exon',
          '-source'  => 'internal', );

    $seqobj->add_SeqFeature($feature1);   # Add the SeqFeature to the parent
    $seqobj->add_SeqFeature($feature2);   # Add the SeqFeature to the parent

    # Once the features and annotations have been associated
    # with the Seq, they can be with retrieved, eg:
    @topfeatures = $seqobj->top_SeqFeatures(); # just top level, or
    @allfeatures = $seqobj->all_SeqFeatures(); # descend into sub features
    $feat = $allfeatures[0];
    $other = $allfeatures[1];

    print $outputfh " Total number of sequence features is: ", scalar @allfeatures, " \n";

    # The individual components of a SeqFeature can also be set
    # or retrieved with methods including:
    # attributes which return numbers
    $feat->start;          # start position
    $feat->end;            # end position
    $feat->strand;         # 1 means forward, -1 reverse, 0 not relevant
    # attributes which return strings
    $feat->primary_tag;    # the main 'name' of the sequence feature,  eg, 'exon'
    $feat->source_tag;     # where the feature comes from, eg'BLAST'
    # attributes which return Bio::PrimarySeq objects
    $feat->seq;            # the sequence between start,end
    $feat->entire_seq;     # the entire sequence

    print $outputfh " The primary tag of the feature is: ", $feat->primary_tag, "   \n";
    print $outputfh " The first feature begins at location ", $feat->start, " \n";
    print $outputfh "  ends at location ", $feat->end, " \n";
    print $outputfh "  and is located on strand ", $feat->strand, " \n";

    # other useful methods include
    $answer = $feat->overlaps($other);  # do SeqFeature $feat and SeqFeature $other overlap?
    print $outputfh " Feature 1 does ", ($answer)? "":"not ", " overlap Feature2. \n";

    $answer = $feat->contains($other); # is $other completely within $feat?
    print $outputfh " Feature 1 does ", ($answer)? "":"not ", " contain Feature2. \n";

    $answer = $feat->equals($other);   # do $feat and $other completely $agree?
    print $outputfh " Feature 1 does ", ($answer)? "":"not ", " equal Feature2. \n";

    $feat->sub_SeqFeature();  # create/access an array of subsequence features

    return 1;
} ;


#################################################
#  largeseqs ():
#

$largeseqs = sub {

    print $outputfh "\nBeginning largeseqs example... \n";
    # III.7.3 Representing large sequences
    my ( $tmpfile, $seqio, $pseq, $plength, $last_4);


    $tmpfile = Bio::Root::IO->catfile("t","data","largefastatest.out") ;
    $seqio = new Bio::SeqIO('-format'=>'largefasta',
                            '-file'  =>Bio::Root::IO->catfile("t","data","genomic-seq.fasta"));
    $pseq = $seqio->next_seq();
    $plength = $pseq->length();

    print $outputfh " The length of the sequence ",
    $pseq->display_id()," is $plength  \n";
    $last_4 = $pseq->subseq($plength-3,$plength);
    print $outputfh " The final four residues are $last_4 \n";

    #END { unlink $tmpfile; }
    unlink $tmpfile;

    return 1;
} ;


#################################################
# liveseqs  ():
#

$liveseqs = sub {

    use Bio::LiveSeq::IO::BioPerl;
    my ($loader, $gene, $id, $maxstart);

    print $outputfh "\nBeginning liveseqs example... \n";
    # Representing changing sequences (LiveSeq)

    $loader=Bio::LiveSeq::IO::BioPerl->load('-db'=>"EMBL",
                                            '-file'=>Bio::Root::IO->catfile("t","data","factor7.embl"));
    $gene=$loader->gene2liveseq('-gene_name' => "factor7");
    $id = $gene->get_DNA->display_id ;
    print $outputfh " The id of the gene is $id , \n";
    $maxstart = $gene->maxtranscript->start;
    print $outputfh " The start position of the max transcript is $maxstart , \n";

    return 1;
} ;


#################################################
# run_struct  ():
#

$run_struct = sub {
  use Bio::Root::IO;
  eval { require Bio::Structure::Entry;
         require Bio::Structure::IO;
       };
  if ( $@ ){
    print STDERR "Cannot find Bio::Structure modules\n";
    print STDERR "Cannot run run_struct:\n";
    return 0;
  } else {
    print $outputfh "\nBeginning Structure object example... \n";
    # testing PDB format
    my $pdb_file = Bio::Root::IO->catfile("t","data","pdb1bpt.ent"); 
    my $structio = Bio::Structure::IO->new(-file  => $pdb_file,
                                           -format=> 'PDB');
    my $struc = $structio->next_structure;
    my ($chain) = $struc->chain;
    print $outputfh " The current chain is ",  $chain->id ," \n";
    my $pseq = $struc->seqres;
    print $outputfh " The first 20 residues of the sequence corresponding " .
    "to this structure are " . $pseq->subseq(1,20) . " \n";
    return 1;
  }
} ;





#################################################
# run_map  ():
#

$run_map = sub {

use Bio::MapIO;
use Bio::Root::IO;

print $outputfh "\nBeginning MapIO example... \n";
my $mapio = new Bio::MapIO(
			    '-format' => 'mapmaker',
			    '-file'   => Bio::Root::IO->catfile('t','data', 
			    'mapmaker.out'));

my $map = $mapio->next_map;

print $outputfh " The type of the map is " , $map->type  ," \n";
print $outputfh " The units of the map are " , $map->units  ," \n";

my $count = 0;
foreach my $marker ( $map->each_element ) {
    print $outputfh " The marker ", $marker->name," is at ordered position " ,  $marker->position->order  ," \n";
    if ($count++ >= 5) {return 1};
}


    return 1;
} ;

#################################################
# run_tree  ():
#

$run_tree = sub {

use Bio::TreeIO;
use Bio::Root::IO;

print $outputfh "\nBeginning phylogenetic tree example... \n";

my $treeio = new Bio::TreeIO( -format => 'newick',
			    -file   => Bio::Root::IO->catfile('t','data', 
							       'cysprot1b.newick'));

my $tree = $treeio->next_tree;
my @nodes = $tree->get_nodes;

 foreach my $node ( $tree->get_root_node()->each_Descendent() ) {
	print $outputfh "node id and branch length: ", $node->to_string(), "\n";
	my @ch = $node->each_Descendent();
	if( @ch ) {
	    print $outputfh "\tchildren are: \n";
	    foreach my $node ( $node->each_Descendent() ) {
		print $outputfh "\t\t id and length: ", $node->to_string(), "\n";
	    }
	}
    }
    return 1;
} ;



#################################################
# run_perl  ():
#

$run_perl = sub {
    use Bio::Perl qw( read_sequence 
		      read_all_sequences 
		      write_sequence 
		      new_sequence 
		      get_sequence );

    print $outputfh "\nBeginning example of sequence manipulation without explicit Seq objects... \n";

    # getting a sequence from a database (assummes internet connection)
 
    my $seq_object;
    eval { 
	$seq_object = get_sequence('swissprot',"ROA1_HUMAN");
    };
    unless( $seq_object ) { return 0 } # deal with case when
    # we're missing a necessary module and this returns undef


    # sequences are Bio::Seq objects, so the following methods work
    # (for more info see Bio::Seq documentation - try perldoc Bio::Seq)

    print $outputfh "Name of sequence retrieved from swissprot is ",$seq_object->display_id,"\n";
    print $outputfh "Sequence acc  is ",$seq_object->accession_number,"\n";
    print $outputfh "First 5 residues are ",$seq_object->subseq(1,5),"\n";

  # getting sequence data from disk
    $seq_object = read_sequence($amino_seq_file,'fasta'); 
    print $outputfh "Name of sequence retrieved from disk is ",$seq_object->display_id,"\n";
   return 1;
} ;


#################################################
# demo_variations  ():
#

$demo_variations = sub {

    print $outputfh "\nBeginning demo_variations example... \n";

    # III.7.5 Representing related sequences
    # - mutations, polymorphisms etc (Allele, SeqDiff,)

    use Bio::Variation::SeqDiff;
    use Bio::Variation::Allele;
    use Bio::Variation::DNAMutation;
    my ($a1, $a2, $dnamut, $seqDiff, @current_variants);

    $a1 = Bio::Variation::Allele->new;
    $a1->seq('aaaa');
    $a2 = Bio::Variation::Allele->new;
    $a2->seq('ttat');

    $dnamut = Bio::Variation::DNAMutation->new
        ('-start'  => 1000,
         '-length'  => 4,
         '-upStreamSeq'  => 'actggg',
         '-proof'  => 'experimental',
         '-isMutation' => 1, );
    $dnamut->allele_ori($a1);
    $dnamut->add_Allele($a2);
    $seqDiff = Bio::Variation::SeqDiff->new
        ('-id' => 'M20132',
         '-alphabet' => 'rna',
         #$seqDiff = Bio::Variation::SeqDiff->new
         #( '-id' => 'M20132', '-alphabet' => 'RNA',
         '-gene_symbol' => 'AR',
         '-chromosome' => 'X',
         '-numbering' => 'coding');
    # add it to a SeqDiff container object
    $seqDiff->add_Variant($dnamut);
    @current_variants = $seqDiff->each_Variant();
    print $outputfh " The original sequence at current variation is ",
    $current_variants[0]->allele_ori->seq ," \n";
    print $outputfh " The mutated sequence is ",
    $current_variants[0]->allele_mut->seq ," \n";
    print $outputfh " The upstream sequence is ",
    $current_variants[0]->upStreamSeq ," \n";

    return 1;
} ;


#################################################
#  demo_xml ():
#

$demo_xml = sub {

    print $outputfh "\nBeginning demo_xml example... \n";
    my ($str, $seqobj, $id, @feats, $first_primary_tag);

    # III.8.4 Sequence XML representations
    # - generation and parsing (SeqIO::game)

    eval { 
	require XML::Parser;
	$str = Bio::SeqIO->new('-file'=>
			       Bio::Root::IO->catfile("t","data","test.game"),
			       '-format' => 'game'); };
    if ( $@ ) {
	print STDERR "Cannot run demo_xml\n";
	print STDERR "\tProblem parsing GAME format or missing necessary installed modules XML::Parser XML::Parser::PerlSAX\n";
	return 0;
    } else {
      $seqobj = $str->next_seq();
      # $seq = $str->next_primary_seq();
      # $id = $seq->id;

      print $outputfh "Seq object display id is ", $seqobj->display_id(),
      "\n"; # the human read-able id of the sequence
      print $outputfh "The sequence description is: \n";
      print $outputfh "   ", $seqobj->desc(), " \n";
      print $outputfh "Acc num is ", $seqobj->accession_number(),
      " \n"; # when there, the accession number
      print $outputfh "Alphabet is ", $seqobj->alphabet(),
      " \n";    # one of 'dna','rna','protein'

      @feats = $seqobj->all_SeqFeatures();
      $first_primary_tag = $feats[0]->primary_tag;
      print $outputfh " Total number of sequence features is: ", 
      scalar @feats, "\n";
      print $outputfh " The primary tag of the first feature is: ",
      $first_primary_tag, "\n";
      print $outputfh " The first feature begins at location ", 
      $feats[0]->start," \n";
      print $outputfh "  and ends at location ", $feats[0]->end, " \n";

      return 1;
   }
} ;


################################################
#  other_seq_utilities ():
#

$other_seq_utilities = sub {

    use Bio::Tools::OddCodes;
    use Bio::Tools::SeqPattern;
    use Bio::Tools::CodonTable;

    my ( $oddcode_obj, $amino_obj, $in, $infile, $chargeseq, $chemseq);
    my (@ii, $i, @res, $myCodonTable);
    my ( $pattern,$pattern_obj, $pattern_obj2, $pattern_obj3);

    print $outputfh "\nBeginning sequence utilities example... \n";

    # III.4.6 Identifying amino acid characteristics
    # - e.g. charge, hydrophobicity (OddCodes)
    $infile = $amino_seq_file;
    $in  = Bio::SeqIO->new('-file' => $infile ,
                           '-format' => 'Fasta');
    $amino_obj = $in->next_seq->trunc(1,20);
    $oddcode_obj  =  Bio::Tools::OddCodes->new($amino_obj);
    print $outputfh "Initial sequence is: \n ", $amino_obj->seq(), " \n";
    $chargeseq = $oddcode_obj->charge;
    # Note OddCodes returns a reference to the desired
    # sequence, not the sequence itself.
    print $outputfh "Sequence in \'charge\' alphabet is : \n ",$$chargeseq, " \n";
    $chemseq = $oddcode_obj->chemical;
    print $outputfh "Sequence in \'chemical\' alphabet is : \n ",$$chemseq, " \n";

    # III.4.2.1 non-standard nucleotide translation tables (CodonTable)

    # create a table object by giving an ID
    $myCodonTable = Bio::Tools::CodonTable -> new ( '-id' => 16);
    print $outputfh "\nThe name of the current codon table is ",
    $myCodonTable->name() , " \n";

    # translate some codons
    @ii  = qw(act acc att ggg ttt aaa ytr yyy);
    @res =();
    for $i (0..$#ii) { $res[$i] = $myCodonTable->translate($ii[$i]); }
    print $outputfh "\nWith the current codon table, the sequence \n ",
    @ii, "\n is translated as \n" , @res, " \n";

    # III.4.2.2 utilities for ambiguous residues (SeqPattern, IUPAC)
    # III.4.2.3 regex-like nucleotide pattern manipulation

    print $outputfh "\nBeginning demo of SeqPattern object \n ";

    $pattern     = '(CCCCT)N{1,200}(agyyg)N{1,80}(agggg)';
    print $outputfh "\nInput regular expression = $pattern \n ";
    $pattern_obj = new Bio::Tools::SeqPattern('-SEQ' =>$pattern,
                                              '-TYPE' =>'dna');
    $pattern_obj2  = $pattern_obj->revcom();
    print $outputfh "\nReverse-complemented expression = ",$pattern_obj2->str, "\n ";
    $pattern_obj3 = $pattern_obj->revcom(1); ## returns expanded rev complement pattern.
    print $outputfh "\nExpanded reverse-complemented expression = ",$pattern_obj3->str, "\n ";
    #$pattern_obj->revcom(1); ## returns expanded rev complement pattern.

    return 1;
} ;

sub run_examples {
    @runlist = @_;
    @_ = ();
    if (scalar(@runlist)==0) {&$display_help;}; # display help if no option
    if( $runlist[0] == -1 ) { return }
    if ($runlist[0] == 0) {@runlist = (1..22); }; # argument = 0 means run tests 1 thru 22
    foreach $n  (@runlist) {
        if ($n ==100) {my $object = $runlist[1]; &$bpinspect1($object); last;}
        if ($n ==1) {&$sequence_manipulations; next;}
        if ($n ==2) {&$seqstats_and_seqwords; next;}
        if ($n ==3) {&$restriction_and_sigcleave; next;}
        if ($n ==4) {&$other_seq_utilities; next;}
        if ($n ==5) {&$run_perl; next;}
        if ($n ==6) {&$searchio_parsing; next;}
        if ($n ==7) {&$bplite_parsing; next;}
        if ($n ==8) {&$hmmer_parsing; next;}
        if ($n ==9) {&$simplealign ; next;}
        if ($n ==10) {&$gene_prediction_parsing; next;}
        if ($n ==11) {&$access_remote_db; next;}
        if ($n ==12) {&$index_local_db; next;}
        if ($n ==13) {&$fetch_local_db; next;}
        if ($n ==14) {&$sequence_annotation; next;}
        if ($n ==15) {&$largeseqs; next;}
        if ($n ==16) {&$liveseqs; next;}
        if ($n ==17) {&$run_struct; next;}
        if ($n ==18) {&$demo_variations; next;}
        if ($n ==19) {&$demo_xml; next;}
        if ($n ==20) {&$run_tree; next;}
        if ($n ==21) {&$run_map; next;}
        if ($n ==22) {&$run_remoteblast; next;}
        if ($n ==23) {&$run_standaloneblast; next;}
        if ($n ==24) {&$run_clustalw_tcoffee; next;}
        if ($n ==25) {&$run_psw_bl2seq; next;}
         &$display_help;
    }
    1;
}
#################################################
# bpinspect1  ():
#
#  Subroutine that identifies from which ancestor module each method
#  of an object is derived
#

$bpinspect1 = sub {
    my ($object, $object_class,$package );
    my @package_list = ();
    $object = shift;
#    ($object_class = $object) =~ s/::/\//g;  # replace "::" with "/"
#    $object_class = $object_class . ".pm";
    $object_class = $object . ".pm";
    eval { require $object_class;};
    # eval causes replacement of "::" with "/" or "\"

    my $method_hash = $object->methods('all');

    print $outputfh " \n ***Methods for Object $object ********  \n";
# get all the *unique* package names providing methods
    my %seen=();
    foreach $package  (values %$method_hash) {
        push(@package_list, $package) unless $seen{$package}++;
    }
    for $package (sort @package_list) {
        print $outputfh " \n\n Methods taken from package $package  \n";
        my $out_count = 1;
        for my $method (sort keys %$method_hash) {
            if ($$method_hash{$method} eq $package ) {
            print $outputfh " $method  ";
            $out_count++;
                if ($out_count == 7) {
                        print $outputfh " \n";    # keeps output line from getting too long
                        $out_count = 1;
                }
            }
         }
     }
    print $outputfh "\n";

# The following subroutine is based closely on Mark Summerfield's and Piers
# Cawley's clever Class_Methods_Introspection program
#
    package UNIVERSAL;
    sub methods {
        my ($class, $types) = @_;
        $class = ref $class || $class;
        $types ||= '';
        my %classes_seen;
        my %methods;
        my @class = ($class);

        no strict 'refs';
        while ($class = shift @class) {
            next if $classes_seen{$class}++;
            unshift @class, @{"${class}::ISA"} if $types eq 'all';
            # Based on methods_via() in perl5db.pl
            for my $method (grep {not /^[(_]/ and
                                  defined &{${"${class}::"}{$_}}}
                            keys %{"${class}::"}) {
		next if exists $methods{$method}; # method already found in heirarchy
                $methods{$method} = $class;        
            }
        }

        wantarray ? keys %methods : \%methods;
    }
    return 1;
} ;

    if( defined $ARGV[0] && $ARGV[0] == -1 ) {
	open(OUT, ">bptutorial.out") || die("cannot open outputfile: $!");
	$outputfh = *OUT;
    }
    foreach my $num (@ARGV) {
       if ( !(-d "t/data") && 
	       grep /^$num$/,(23,4,1,14,12,13,6,7,8,9,24,25,10,5,15,16,17,20,21) ) {
	  print $outputfh "Example $num uses files in t/data\nDirectory t/data not found\n";
	  exit;
       }
    }
    &run_examples(@ARGV);

## End of "main"
1;