Spaces:
No application file
No application file
File size: 118,856 Bytes
b7731cd |
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 |
# Copyright 2000 Andrew Dalke.
# Copyright 2000-2002 Brad Chapman.
# Copyright 2004-2005, 2010 by M de Hoon.
# Copyright 2007-2020 by Peter Cock.
# All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Provide objects to represent biological sequences.
See also the Seq_ wiki and the chapter in our tutorial:
- `HTML Tutorial`_
- `PDF Tutorial`_
.. _Seq: http://biopython.org/wiki/Seq
.. _`HTML Tutorial`: http://biopython.org/DIST/docs/tutorial/Tutorial.html
.. _`PDF Tutorial`: http://biopython.org/DIST/docs/tutorial/Tutorial.pdf
"""
import array
import numbers
import warnings
from abc import ABC
from abc import abstractmethod
from Bio import BiopythonDeprecationWarning
from Bio import BiopythonWarning
from Bio.Data import CodonTable
from Bio.Data import IUPACData
def _maketrans(complement_mapping):
"""Make a python string translation table (PRIVATE).
Arguments:
- complement_mapping - a dictionary such as ambiguous_dna_complement
and ambiguous_rna_complement from Data.IUPACData.
Returns a translation table (a bytes object of length 256) for use with
the python string's translate method to use in a (reverse) complement.
Compatible with lower case and upper case sequences.
For internal use only.
"""
keys = "".join(complement_mapping.keys()).encode("ASCII")
values = "".join(complement_mapping.values()).encode("ASCII")
return bytes.maketrans(keys + keys.lower(), values + values.lower())
ambiguous_dna_complement = dict(IUPACData.ambiguous_dna_complement)
ambiguous_dna_complement["U"] = ambiguous_dna_complement["T"]
_dna_complement_table = _maketrans(ambiguous_dna_complement)
del ambiguous_dna_complement
ambiguous_rna_complement = dict(IUPACData.ambiguous_rna_complement)
ambiguous_rna_complement["T"] = ambiguous_rna_complement["U"]
_rna_complement_table = _maketrans(ambiguous_rna_complement)
del ambiguous_rna_complement
class SequenceDataAbstractBaseClass(ABC):
"""Abstract base class for sequence content providers.
Most users will not need to use this class. It is used internally as a base
class for sequence content provider classes such as _UndefinedSequenceData
defined in this module, and _TwoBitSequenceData in Bio.SeqIO.TwoBitIO.
Instances of these classes can be used instead of a ``bytes`` object as the
data argument when creating a Seq object, and provide the sequence content
only when requested via ``__getitem__``. This allows lazy parsers to load
and parse sequence data from a file only for the requested sequence regions,
and _UndefinedSequenceData instances to raise an exception when undefined
sequence data are requested.
Future implementations of lazy parsers that similarly provide on-demand
parsing of sequence data should use a subclass of this abstract class and
implement the abstract methods ``__len__`` and ``__getitem__``:
* ``__len__`` must return the sequence length;
* ``__getitem__`` must return
* a ``bytes`` object for the requested region; or
* a new instance of the subclass for the requested region; or
* raise an ``UndefinedSequenceError``.
Calling ``__getitem__`` for a sequence region of size zero should always
return an empty ``bytes`` object.
Calling ``__getitem__`` for the full sequence (as in data[:]) should
either return a ``bytes`` object with the full sequence, or raise an
``UndefinedSequenceError``.
Subclasses of SequenceDataAbstractBaseClass must call ``super().__init__()``
as part of their ``__init__`` method.
"""
__slots__ = ()
def __init__(self):
"""Check if ``__getitem__`` returns a bytes-like object."""
assert self[:0] == b""
@abstractmethod
def __len__(self):
pass
@abstractmethod
def __getitem__(self, key):
pass
def __bytes__(self):
return self[:]
def __hash__(self):
return hash(bytes(self))
def __eq__(self, other):
return bytes(self) == other
def __lt__(self, other):
return bytes(self) < other
def __le__(self, other):
return bytes(self) <= other
def __gt__(self, other):
return bytes(self) > other
def __ge__(self, other):
return bytes(self) >= other
def __add__(self, other):
try:
return bytes(self) + bytes(other)
except UndefinedSequenceError:
return NotImplemented
# will be handled by _UndefinedSequenceData.__radd__ or
# by _PartiallyDefinedSequenceData.__radd__
def __radd__(self, other):
return other + bytes(self)
def __mul__(self, other):
return other * bytes(self)
def __contains__(self, item):
return bytes(self).__contains__(item)
def decode(self, encoding="utf-8"):
"""Decode the data as bytes using the codec registered for encoding.
encoding
The encoding with which to decode the bytes.
"""
return bytes(self).decode(encoding)
def count(self, sub, start=None, end=None):
"""Return the number of non-overlapping occurrences of sub in data[start:end].
Optional arguments start and end are interpreted as in slice notation.
This method behaves as the count method of Python strings.
"""
return bytes(self).count(sub, start, end)
def find(self, sub, start=None, end=None):
"""Return the lowest index in data where subsection sub is found.
Return the lowest index in data where subsection sub is found,
such that sub is contained within data[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return bytes(self).find(sub, start, end)
def rfind(self, sub, start=None, end=None):
"""Return the highest index in data where subsection sub is found.
Return the highest index in data where subsection sub is found,
such that sub is contained within data[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return bytes(self).rfind(sub, start, end)
def index(self, sub, start=None, end=None):
"""Return the lowest index in data where subsection sub is found.
Return the lowest index in data where subsection sub is found,
such that sub is contained within data[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the subsection is not found.
"""
return bytes(self).index(sub, start, end)
def rindex(self, sub, start=None, end=None):
"""Return the highest index in data where subsection sub is found.
Return the highest index in data where subsection sub is found,
such that sub is contained within data[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Raise ValueError when the subsection is not found.
"""
return bytes(self).rindex(sub, start, end)
def startswith(self, prefix, start=None, end=None):
"""Return True if data starts with the specified prefix, False otherwise.
With optional start, test data beginning at that position.
With optional end, stop comparing data at that position.
prefix can also be a tuple of bytes to try.
"""
return bytes(self).startswith(prefix, start, end)
def endswith(self, suffix, start=None, end=None):
"""Return True if data ends with the specified suffix, False otherwise.
With optional start, test data beginning at that position.
With optional end, stop comparing data at that position.
suffix can also be a tuple of bytes to try.
"""
return bytes(self).endswith(suffix, start, end)
def split(self, sep=None, maxsplit=-1):
"""Return a list of the sections in the data, using sep as the delimiter.
sep
The delimiter according which to split the data.
None (the default value) means split on ASCII whitespace characters
(space, tab, return, newline, formfeed, vertical tab).
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
"""
return bytes(self).split(sep, maxsplit)
def rsplit(self, sep=None, maxsplit=-1):
"""Return a list of the sections in the data, using sep as the delimiter.
sep
The delimiter according which to split the data.
None (the default value) means split on ASCII whitespace characters
(space, tab, return, newline, formfeed, vertical tab).
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
Splitting is done starting at the end of the data and working to the front.
"""
return bytes(self).rsplit(sep, maxsplit)
def strip(self, chars=None):
"""Strip leading and trailing characters contained in the argument.
If the argument is omitted or None, strip leading and trailing ASCII whitespace.
"""
return bytes(self).strip(chars)
def lstrip(self, chars=None):
"""Strip leading characters contained in the argument.
If the argument is omitted or None, strip leading ASCII whitespace.
"""
return bytes(self).lstrip(chars)
def rstrip(self, chars=None):
"""Strip trailing characters contained in the argument.
If the argument is omitted or None, strip trailing ASCII whitespace.
"""
return bytes(self).rstrip(chars)
def upper(self):
"""Return a copy of data with all ASCII characters converted to uppercase."""
return bytes(self).upper()
def lower(self):
"""Return a copy of data with all ASCII characters converted to lowercase."""
return bytes(self).lower()
def isupper(self):
"""Return True if all ASCII characters in data are uppercase.
If there are no cased characters, the method returns False.
"""
return bytes(self).isupper()
def islower(self):
"""Return True if all ASCII characters in data are lowercase.
If there are no cased characters, the method returns False.
"""
return bytes(self).islower()
def replace(self, old, new):
"""Return a copy with all occurrences of substring old replaced by new."""
return bytes(self).replace(old, new)
def translate(self, table, delete=b""):
"""Return a copy with each character mapped by the given translation table.
table
Translation table, which must be a bytes object of length 256.
All characters occurring in the optional argument delete are removed.
The remaining characters are mapped through the given translation table.
"""
return bytes(self).translate(table, delete)
@property
def defined(self):
"""Return True if the sequence is defined, False if undefined or partially defined.
Zero-length sequences are always considered to be defined.
"""
return True
@property
def defined_ranges(self):
"""Return a tuple of the ranges where the sequence contents is defined.
The return value has the format ((start1, end1), (start2, end2), ...).
"""
length = len(self)
if length > 0:
return ((0, length),)
else:
return ()
class _SeqAbstractBaseClass(ABC):
"""Abstract base class for the Seq and MutableSeq classes (PRIVATE).
Most users will not need to use this class. It is used internally as an
abstract base class for Seq and MutableSeq, as most of their methods are
identical.
"""
__slots__ = ("_data",)
__array_ufunc__ = None # turn off numpy Ufuncs
@abstractmethod
def __init__(self):
pass
def __bytes__(self):
return bytes(self._data)
def __repr__(self):
"""Return (truncated) representation of the sequence."""
data = self._data
if isinstance(data, _UndefinedSequenceData):
return f"Seq(None, length={len(self)})"
if isinstance(data, _PartiallyDefinedSequenceData):
d = {}
for position, seq in data._data.items():
if len(seq) > 60:
start = seq[:54].decode("ASCII")
end = seq[-3:].decode("ASCII")
seq = f"{start}...{end}"
else:
seq = seq.decode("ASCII")
d[position] = seq
return "Seq(%r, length=%d)" % (d, len(self))
if len(data) > 60:
# Shows the last three letters as it is often useful to see if
# there is a stop codon at the end of a sequence.
# Note total length is 54+3+3=60
start = data[:54].decode("ASCII")
end = data[-3:].decode("ASCII")
return f"{self.__class__.__name__}('{start}...{end}')"
else:
data = data.decode("ASCII")
return f"{self.__class__.__name__}('{data}')"
def __str__(self):
"""Return the full sequence as a python string."""
return self._data.decode("ASCII")
def __eq__(self, other):
"""Compare the sequence to another sequence or a string.
Sequences are equal to each other if their sequence contents is
identical:
>>> from Bio.Seq import Seq, MutableSeq
>>> seq1 = Seq("ACGT")
>>> seq2 = Seq("ACGT")
>>> mutable_seq = MutableSeq("ACGT")
>>> seq1 == seq2
True
>>> seq1 == mutable_seq
True
>>> seq1 == "ACGT"
True
Note that the sequence objects themselves are not identical to each
other:
>>> id(seq1) == id(seq2)
False
>>> seq1 is seq2
False
Sequences can also be compared to strings, ``bytes``, and ``bytearray``
objects:
>>> seq1 == "ACGT"
True
>>> seq1 == b"ACGT"
True
>>> seq1 == bytearray(b"ACGT")
True
"""
if isinstance(other, _SeqAbstractBaseClass):
return self._data == other._data
elif isinstance(other, str):
return self._data == other.encode("ASCII")
else:
return self._data == other
def __lt__(self, other):
"""Implement the less-than operand."""
if isinstance(other, _SeqAbstractBaseClass):
return self._data < other._data
elif isinstance(other, str):
return self._data < other.encode("ASCII")
else:
return self._data < other
def __le__(self, other):
"""Implement the less-than or equal operand."""
if isinstance(other, _SeqAbstractBaseClass):
return self._data <= other._data
elif isinstance(other, str):
return self._data <= other.encode("ASCII")
else:
return self._data <= other
def __gt__(self, other):
"""Implement the greater-than operand."""
if isinstance(other, _SeqAbstractBaseClass):
return self._data > other._data
elif isinstance(other, str):
return self._data > other.encode("ASCII")
else:
return self._data > other
def __ge__(self, other):
"""Implement the greater-than or equal operand."""
if isinstance(other, _SeqAbstractBaseClass):
return self._data >= other._data
elif isinstance(other, str):
return self._data >= other.encode("ASCII")
else:
return self._data >= other
def __len__(self):
"""Return the length of the sequence."""
return len(self._data)
def __iter__(self):
"""Return an iterable of the sequence."""
return self._data.decode("ASCII").__iter__()
def __getitem__(self, index):
"""Return a subsequence as a single letter or as a sequence object.
If the index is an integer, a single letter is returned as a Python
string:
>>> seq = Seq('ACTCGACGTCG')
>>> seq[5]
'A'
Otherwise, a new sequence object of the same class is returned:
>>> seq[5:8]
Seq('ACG')
>>> mutable_seq = MutableSeq('ACTCGACGTCG')
>>> mutable_seq[5:8]
MutableSeq('ACG')
"""
if isinstance(index, numbers.Integral):
# Return a single letter as a string
return chr(self._data[index])
else:
# Return the (sub)sequence as another Seq/MutableSeq object
return self.__class__(self._data[index])
def __add__(self, other):
"""Add a sequence or string to this sequence.
>>> from Bio.Seq import Seq, MutableSeq
>>> Seq("MELKI") + "LV"
Seq('MELKILV')
>>> MutableSeq("MELKI") + "LV"
MutableSeq('MELKILV')
"""
if isinstance(other, _SeqAbstractBaseClass):
return self.__class__(self._data + other._data)
elif isinstance(other, str):
return self.__class__(self._data + other.encode("ASCII"))
else:
# If other is a SeqRecord, then SeqRecord's __radd__ will handle
# this. If not, returning NotImplemented will trigger a TypeError.
return NotImplemented
def __radd__(self, other):
"""Add a sequence string on the left.
>>> from Bio.Seq import Seq, MutableSeq
>>> "LV" + Seq("MELKI")
Seq('LVMELKI')
>>> "LV" + MutableSeq("MELKI")
MutableSeq('LVMELKI')
Adding two sequence objects is handled via the __add__ method.
"""
if isinstance(other, str):
return self.__class__(other.encode("ASCII") + self._data)
else:
return NotImplemented
def __mul__(self, other):
"""Multiply sequence by integer.
>>> from Bio.Seq import Seq, MutableSeq
>>> Seq('ATG') * 2
Seq('ATGATG')
>>> MutableSeq('ATG') * 2
MutableSeq('ATGATG')
"""
if not isinstance(other, numbers.Integral):
raise TypeError(f"can't multiply {self.__class__.__name__} by non-int type")
# we would like to simply write
# data = self._data * other
# here, but currently that causes a bug on PyPy if self._data is a
# bytearray and other is a numpy integer. Using this workaround:
data = self._data.__mul__(other)
return self.__class__(data)
def __rmul__(self, other):
"""Multiply integer by sequence.
>>> from Bio.Seq import Seq
>>> 2 * Seq('ATG')
Seq('ATGATG')
"""
if not isinstance(other, numbers.Integral):
raise TypeError(f"can't multiply {self.__class__.__name__} by non-int type")
# we would like to simply write
# data = self._data * other
# here, but currently that causes a bug on PyPy if self._data is a
# bytearray and other is a numpy integer. Using this workaround:
data = self._data.__mul__(other)
return self.__class__(data)
def __imul__(self, other):
"""Multiply the sequence object by other and assign.
>>> from Bio.Seq import Seq
>>> seq = Seq('ATG')
>>> seq *= 2
>>> seq
Seq('ATGATG')
Note that this is different from in-place multiplication. The ``seq``
variable is reassigned to the multiplication result, but any variable
pointing to ``seq`` will remain unchanged:
>>> seq = Seq('ATG')
>>> seq2 = seq
>>> id(seq) == id(seq2)
True
>>> seq *= 2
>>> seq
Seq('ATGATG')
>>> seq2
Seq('ATG')
>>> id(seq) == id(seq2)
False
"""
if not isinstance(other, numbers.Integral):
raise TypeError(f"can't multiply {self.__class__.__name__} by non-int type")
# we would like to simply write
# data = self._data * other
# here, but currently that causes a bug on PyPy if self._data is a
# bytearray and other is a numpy integer. Using this workaround:
data = self._data.__mul__(other)
return self.__class__(data)
def count(self, sub, start=None, end=None):
"""Return a non-overlapping count, like that of a python string.
The number of occurrences of substring argument sub in the
(sub)sequence given by [start:end] is returned as an integer.
Optional arguments start and end are interpreted as in slice
notation.
Arguments:
- sub - a string or another Seq object to look for
- start - optional integer, slice start
- end - optional integer, slice end
e.g.
>>> from Bio.Seq import Seq
>>> my_seq = Seq("AAAATGA")
>>> print(my_seq.count("A"))
5
>>> print(my_seq.count("ATG"))
1
>>> print(my_seq.count(Seq("AT")))
1
>>> print(my_seq.count("AT", 2, -1))
1
HOWEVER, please note because the ``count`` method of Seq and MutableSeq
objects, like that of Python strings, do a non-overlapping search, this
may not give the answer you expect:
>>> "AAAA".count("AA")
2
>>> print(Seq("AAAA").count("AA"))
2
For an overlapping search, use the ``count_overlap`` method:
>>> print(Seq("AAAA").count_overlap("AA"))
3
"""
if isinstance(sub, MutableSeq):
sub = sub._data
elif isinstance(sub, Seq):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
return self._data.count(sub, start, end)
def count_overlap(self, sub, start=None, end=None):
"""Return an overlapping count.
Returns an integer, the number of occurrences of substring
argument sub in the (sub)sequence given by [start:end].
Optional arguments start and end are interpreted as in slice
notation.
Arguments:
- sub - a string or another Seq object to look for
- start - optional integer, slice start
- end - optional integer, slice end
e.g.
>>> from Bio.Seq import Seq
>>> print(Seq("AAAA").count_overlap("AA"))
3
>>> print(Seq("ATATATATA").count_overlap("ATA"))
4
>>> print(Seq("ATATATATA").count_overlap("ATA", 3, -1))
1
For a non-overlapping search, use the ``count`` method:
>>> print(Seq("AAAA").count("AA"))
2
Where substrings do not overlap, ``count_overlap`` behaves the same as
the ``count`` method:
>>> from Bio.Seq import Seq
>>> my_seq = Seq("AAAATGA")
>>> print(my_seq.count_overlap("A"))
5
>>> my_seq.count_overlap("A") == my_seq.count("A")
True
>>> print(my_seq.count_overlap("ATG"))
1
>>> my_seq.count_overlap("ATG") == my_seq.count("ATG")
True
>>> print(my_seq.count_overlap(Seq("AT")))
1
>>> my_seq.count_overlap(Seq("AT")) == my_seq.count(Seq("AT"))
True
>>> print(my_seq.count_overlap("AT", 2, -1))
1
>>> my_seq.count_overlap("AT", 2, -1) == my_seq.count("AT", 2, -1)
True
HOWEVER, do not use this method for such cases because the
count() method is much for efficient.
"""
if isinstance(sub, MutableSeq):
sub = sub._data
elif isinstance(sub, Seq):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
data = self._data
overlap_count = 0
while True:
start = data.find(sub, start, end) + 1
if start != 0:
overlap_count += 1
else:
return overlap_count
def __contains__(self, item):
"""Return True if item is a subsequence of the sequence, and False otherwise.
e.g.
>>> from Bio.Seq import Seq, MutableSeq
>>> my_dna = Seq("ATATGAAATTTGAAAA")
>>> "AAA" in my_dna
True
>>> Seq("AAA") in my_dna
True
>>> MutableSeq("AAA") in my_dna
True
"""
if isinstance(item, _SeqAbstractBaseClass):
item = bytes(item)
elif isinstance(item, str):
item = item.encode("ASCII")
return item in self._data
def find(self, sub, start=None, end=None):
"""Return the lowest index in the sequence where subsequence sub is found.
With optional arguments start and end, return the lowest index in the
sequence such that the subsequence sub is contained within the sequence
region [start:end].
Arguments:
- sub - a string or another Seq or MutableSeq object to search for
- start - optional integer, slice start
- end - optional integer, slice end
Returns -1 if the subsequence is NOT found.
e.g. Locating the first typical start codon, AUG, in an RNA sequence:
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.find("AUG")
3
The next typical start codon can then be found by starting the search
at position 4:
>>> my_rna.find("AUG", 4)
15
"""
if isinstance(sub, _SeqAbstractBaseClass):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
return self._data.find(sub, start, end)
def rfind(self, sub, start=None, end=None):
"""Return the highest index in the sequence where subsequence sub is found.
With optional arguments start and end, return the highest index in the
sequence such that the subsequence sub is contained within the sequence
region [start:end].
Arguments:
- sub - a string or another Seq or MutableSeq object to search for
- start - optional integer, slice start
- end - optional integer, slice end
Returns -1 if the subsequence is NOT found.
e.g. Locating the last typical start codon, AUG, in an RNA sequence:
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.rfind("AUG")
15
The location of the typical start codon before that can be found by
ending the search at position 15:
>>> my_rna.rfind("AUG", end=15)
3
"""
if isinstance(sub, _SeqAbstractBaseClass):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
return self._data.rfind(sub, start, end)
def index(self, sub, start=None, end=None):
"""Return the lowest index in the sequence where subsequence sub is found.
With optional arguments start and end, return the lowest index in the
sequence such that the subsequence sub is contained within the sequence
region [start:end].
Arguments:
- sub - a string or another Seq or MutableSeq object to search for
- start - optional integer, slice start
- end - optional integer, slice end
Raises a ValueError if the subsequence is NOT found.
e.g. Locating the first typical start codon, AUG, in an RNA sequence:
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.index("AUG")
3
The next typical start codon can then be found by starting the search
at position 4:
>>> my_rna.index("AUG", 4)
15
This method performs the same search as the ``find`` method. However,
if the subsequence is not found, ``find`` returns -1 which ``index``
raises a ValueError:
>>> my_rna.index("T")
Traceback (most recent call last):
...
ValueError: ...
>>> my_rna.find("T")
-1
"""
if isinstance(sub, MutableSeq):
sub = sub._data
elif isinstance(sub, Seq):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
return self._data.index(sub, start, end)
def rindex(self, sub, start=None, end=None):
"""Return the highest index in the sequence where subsequence sub is found.
With optional arguments start and end, return the highest index in the
sequence such that the subsequence sub is contained within the sequence
region [start:end].
Arguments:
- sub - a string or another Seq or MutableSeq object to search for
- start - optional integer, slice start
- end - optional integer, slice end
Returns -1 if the subsequence is NOT found.
e.g. Locating the last typical start codon, AUG, in an RNA sequence:
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.rindex("AUG")
15
The location of the typical start codon before that can be found by
ending the search at position 15:
>>> my_rna.rindex("AUG", end=15)
3
This method performs the same search as the ``rfind`` method. However,
if the subsequence is not found, ``rfind`` returns -1 which ``rindex``
raises a ValueError:
>>> my_rna.rindex("T")
Traceback (most recent call last):
...
ValueError: ...
>>> my_rna.rfind("T")
-1
"""
if isinstance(sub, MutableSeq):
sub = sub._data
elif isinstance(sub, Seq):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
return self._data.rindex(sub, start, end)
def startswith(self, prefix, start=None, end=None):
"""Return True if the sequence starts with the given prefix, False otherwise.
Return True if the sequence starts with the specified prefix
(a string or another Seq object), False otherwise.
With optional start, test sequence beginning at that position.
With optional end, stop comparing sequence at that position.
prefix can also be a tuple of strings to try. e.g.
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.startswith("GUC")
True
>>> my_rna.startswith("AUG")
False
>>> my_rna.startswith("AUG", 3)
True
>>> my_rna.startswith(("UCC", "UCA", "UCG"), 1)
True
"""
if isinstance(prefix, tuple):
prefix = tuple(
bytes(p) if isinstance(p, _SeqAbstractBaseClass) else p.encode("ASCII")
for p in prefix
)
elif isinstance(prefix, _SeqAbstractBaseClass):
prefix = bytes(prefix)
elif isinstance(prefix, str):
prefix = prefix.encode("ASCII")
return self._data.startswith(prefix, start, end)
def endswith(self, suffix, start=None, end=None):
"""Return True if the sequence ends with the given suffix, False otherwise.
Return True if the sequence ends with the specified suffix
(a string or another Seq object), False otherwise.
With optional start, test sequence beginning at that position.
With optional end, stop comparing sequence at that position.
suffix can also be a tuple of strings to try. e.g.
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.endswith("UUG")
True
>>> my_rna.endswith("AUG")
False
>>> my_rna.endswith("AUG", 0, 18)
True
>>> my_rna.endswith(("UCC", "UCA", "UUG"))
True
"""
if isinstance(suffix, tuple):
suffix = tuple(
bytes(p) if isinstance(p, _SeqAbstractBaseClass) else p.encode("ASCII")
for p in suffix
)
elif isinstance(suffix, _SeqAbstractBaseClass):
suffix = bytes(suffix)
elif isinstance(suffix, str):
suffix = suffix.encode("ASCII")
return self._data.endswith(suffix, start, end)
def split(self, sep=None, maxsplit=-1):
"""Return a list of subsequences when splitting the sequence by separator sep.
Return a list of the subsequences in the sequence (as Seq objects),
using sep as the delimiter string. If maxsplit is given, at
most maxsplit splits are done. If maxsplit is omitted, all
splits are made.
For consistency with the ``split`` method of Python strings, any
whitespace (tabs, spaces, newlines) is a separator if sep is None, the
default value
e.g.
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_aa = my_rna.translate()
>>> my_aa
Seq('VMAIVMGR*KGAR*L')
>>> for pep in my_aa.split("*"):
... pep
Seq('VMAIVMGR')
Seq('KGAR')
Seq('L')
>>> for pep in my_aa.split("*", 1):
... pep
Seq('VMAIVMGR')
Seq('KGAR*L')
See also the rsplit method, which splits the sequence starting from the
end:
>>> for pep in my_aa.rsplit("*", 1):
... pep
Seq('VMAIVMGR*KGAR')
Seq('L')
"""
if isinstance(sep, _SeqAbstractBaseClass):
sep = bytes(sep)
elif isinstance(sep, str):
sep = sep.encode("ASCII")
return [Seq(part) for part in self._data.split(sep, maxsplit)]
def rsplit(self, sep=None, maxsplit=-1):
"""Return a list of subsequences by splitting the sequence from the right.
Return a list of the subsequences in the sequence (as Seq objects),
using sep as the delimiter string. If maxsplit is given, at
most maxsplit splits are done. If maxsplit is omitted, all
splits are made.
For consistency with the ``rsplit`` method of Python strings, any
whitespace (tabs, spaces, newlines) is a separator if sep is None, the
default value
e.g.
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_aa = my_rna.translate()
>>> my_aa
Seq('VMAIVMGR*KGAR*L')
>>> for pep in my_aa.rsplit("*"):
... pep
Seq('VMAIVMGR')
Seq('KGAR')
Seq('L')
>>> for pep in my_aa.rsplit("*", 1):
... pep
Seq('VMAIVMGR*KGAR')
Seq('L')
See also the split method, which splits the sequence starting from the
beginning:
>>> for pep in my_aa.split("*", 1):
... pep
Seq('VMAIVMGR')
Seq('KGAR*L')
"""
if isinstance(sep, _SeqAbstractBaseClass):
sep = bytes(sep)
elif isinstance(sep, str):
sep = sep.encode("ASCII")
return [Seq(part) for part in self._data.rsplit(sep, maxsplit)]
def strip(self, chars=None, inplace=False):
"""Return a sequence object with leading and trailing ends stripped.
With default arguments, leading and trailing whitespace is removed:
>>> seq = Seq(" ACGT ")
>>> seq.strip()
Seq('ACGT')
>>> seq
Seq(' ACGT ')
If ``chars`` is given and not ``None``, remove characters in ``chars``
instead. The order of the characters to be removed is not important:
>>> Seq("ACGTACGT").strip("TGCA")
Seq('')
A copy of the sequence is returned if ``inplace`` is ``False`` (the
default value). If ``inplace`` is ``True``, the sequence is stripped
in-place and returned.
>>> seq = MutableSeq(" ACGT ")
>>> seq.strip(inplace=False)
MutableSeq('ACGT')
>>> seq
MutableSeq(' ACGT ')
>>> seq.strip(inplace=True)
MutableSeq('ACGT')
>>> seq
MutableSeq('ACGT')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if ``strip``
is called on a ``Seq`` object with ``inplace=True``.
See also the lstrip and rstrip methods.
"""
if isinstance(chars, _SeqAbstractBaseClass):
chars = bytes(chars)
elif isinstance(chars, str):
chars = chars.encode("ASCII")
try:
data = self._data.strip(chars)
except TypeError:
raise TypeError(
"argument must be None or a string, Seq, MutableSeq, or bytes-like object"
) from None
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[:] = data
return self
else:
return self.__class__(data)
def lstrip(self, chars=None, inplace=False):
"""Return a sequence object with leading and trailing ends stripped.
With default arguments, leading whitespace is removed:
>>> seq = Seq(" ACGT ")
>>> seq.lstrip()
Seq('ACGT ')
>>> seq
Seq(' ACGT ')
If ``chars`` is given and not ``None``, remove characters in ``chars``
from the leading end instead. The order of the characters to be removed
is not important:
>>> Seq("ACGACGTTACG").lstrip("GCA")
Seq('TTACG')
A copy of the sequence is returned if ``inplace`` is ``False`` (the
default value). If ``inplace`` is ``True``, the sequence is stripped
in-place and returned.
>>> seq = MutableSeq(" ACGT ")
>>> seq.lstrip(inplace=False)
MutableSeq('ACGT ')
>>> seq
MutableSeq(' ACGT ')
>>> seq.lstrip(inplace=True)
MutableSeq('ACGT ')
>>> seq
MutableSeq('ACGT ')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``lstrip`` is called on a ``Seq`` object with ``inplace=True``.
See also the strip and rstrip methods.
"""
if isinstance(chars, _SeqAbstractBaseClass):
chars = bytes(chars)
elif isinstance(chars, str):
chars = chars.encode("ASCII")
try:
data = self._data.lstrip(chars)
except TypeError:
raise TypeError(
"argument must be None or a string, Seq, MutableSeq, or bytes-like object"
) from None
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[:] = data
return self
else:
return self.__class__(data)
def rstrip(self, chars=None, inplace=False):
"""Return a sequence object with trailing ends stripped.
With default arguments, trailing whitespace is removed:
>>> seq = Seq(" ACGT ")
>>> seq.rstrip()
Seq(' ACGT')
>>> seq
Seq(' ACGT ')
If ``chars`` is given and not ``None``, remove characters in ``chars``
from the trailing end instead. The order of the characters to be
removed is not important:
>>> Seq("ACGACGTTACG").rstrip("GCA")
Seq('ACGACGTT')
A copy of the sequence is returned if ``inplace`` is ``False`` (the
default value). If ``inplace`` is ``True``, the sequence is stripped
in-place and returned.
>>> seq = MutableSeq(" ACGT ")
>>> seq.rstrip(inplace=False)
MutableSeq(' ACGT')
>>> seq
MutableSeq(' ACGT ')
>>> seq.rstrip(inplace=True)
MutableSeq(' ACGT')
>>> seq
MutableSeq(' ACGT')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``rstrip`` is called on a ``Seq`` object with ``inplace=True``.
See also the strip and lstrip methods.
"""
if isinstance(chars, _SeqAbstractBaseClass):
chars = bytes(chars)
elif isinstance(chars, str):
chars = chars.encode("ASCII")
try:
data = self._data.rstrip(chars)
except TypeError:
raise TypeError(
"argument must be None or a string, Seq, MutableSeq, or bytes-like object"
) from None
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[:] = data
return self
else:
return self.__class__(data)
def upper(self, inplace=False):
"""Return the sequence in upper case.
An upper-case copy of the sequence is returned if inplace is False,
the default value:
>>> from Bio.Seq import Seq, MutableSeq
>>> my_seq = Seq("VHLTPeeK*")
>>> my_seq
Seq('VHLTPeeK*')
>>> my_seq.lower()
Seq('vhltpeek*')
>>> my_seq.upper()
Seq('VHLTPEEK*')
>>> my_seq
Seq('VHLTPeeK*')
The sequence is modified in-place and returned if inplace is True:
>>> my_seq = MutableSeq("VHLTPeeK*")
>>> my_seq
MutableSeq('VHLTPeeK*')
>>> my_seq.lower()
MutableSeq('vhltpeek*')
>>> my_seq.upper()
MutableSeq('VHLTPEEK*')
>>> my_seq
MutableSeq('VHLTPeeK*')
>>> my_seq.lower(inplace=True)
MutableSeq('vhltpeek*')
>>> my_seq
MutableSeq('vhltpeek*')
>>> my_seq.upper(inplace=True)
MutableSeq('VHLTPEEK*')
>>> my_seq
MutableSeq('VHLTPEEK*')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``upper`` is called on a ``Seq`` object with ``inplace=True``.
See also the ``lower`` method.
"""
data = self._data.upper()
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[:] = data
return self
else:
return self.__class__(data)
def lower(self, inplace=False):
"""Return the sequence in lower case.
An lower-case copy of the sequence is returned if inplace is False,
the default value:
>>> from Bio.Seq import Seq, MutableSeq
>>> my_seq = Seq("VHLTPeeK*")
>>> my_seq
Seq('VHLTPeeK*')
>>> my_seq.lower()
Seq('vhltpeek*')
>>> my_seq.upper()
Seq('VHLTPEEK*')
>>> my_seq
Seq('VHLTPeeK*')
The sequence is modified in-place and returned if inplace is True:
>>> my_seq = MutableSeq("VHLTPeeK*")
>>> my_seq
MutableSeq('VHLTPeeK*')
>>> my_seq.lower()
MutableSeq('vhltpeek*')
>>> my_seq.upper()
MutableSeq('VHLTPEEK*')
>>> my_seq
MutableSeq('VHLTPeeK*')
>>> my_seq.lower(inplace=True)
MutableSeq('vhltpeek*')
>>> my_seq
MutableSeq('vhltpeek*')
>>> my_seq.upper(inplace=True)
MutableSeq('VHLTPEEK*')
>>> my_seq
MutableSeq('VHLTPEEK*')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``lower`` is called on a ``Seq`` object with ``inplace=True``.
See also the ``upper`` method.
"""
data = self._data.lower()
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[:] = data
return self
else:
return self.__class__(data)
def isupper(self):
"""Return True if all ASCII characters in data are uppercase.
If there are no cased characters, the method returns False.
"""
return self._data.isupper()
def islower(self):
"""Return True if all ASCII characters in data are lowercase.
If there are no cased characters, the method returns False.
"""
return self._data.islower()
def translate(
self, table="Standard", stop_symbol="*", to_stop=False, cds=False, gap="-"
):
"""Turn a nucleotide sequence into a protein sequence by creating a new sequence object.
This method will translate DNA or RNA sequences. It should not
be used on protein sequences as any result will be biologically
meaningless.
Arguments:
- table - Which codon table to use? This can be either a name
(string), an NCBI identifier (integer), or a CodonTable
object (useful for non-standard genetic codes). This
defaults to the "Standard" table.
- stop_symbol - Single character string, what to use for
terminators. This defaults to the asterisk, "*".
- to_stop - Boolean, defaults to False meaning do a full
translation continuing on past any stop codons (translated as the
specified stop_symbol). If True, translation is terminated at
the first in frame stop codon (and the stop_symbol is not
appended to the returned protein sequence).
- cds - Boolean, indicates this is a complete CDS. If True,
this checks the sequence starts with a valid alternative start
codon (which will be translated as methionine, M), that the
sequence length is a multiple of three, and that there is a
single in frame stop codon at the end (this will be excluded
from the protein sequence, regardless of the to_stop option).
If these tests fail, an exception is raised.
- gap - Single character string to denote symbol used for gaps.
Defaults to the minus sign.
A ``Seq`` object is returned if ``translate`` is called on a ``Seq``
object; a ``MutableSeq`` object is returned if ``translate`` is called
pn a ``MutableSeq`` object.
e.g. Using the standard table:
>>> coding_dna = Seq("GTGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG")
>>> coding_dna.translate()
Seq('VAIVMGR*KGAR*')
>>> coding_dna.translate(stop_symbol="@")
Seq('VAIVMGR@KGAR@')
>>> coding_dna.translate(to_stop=True)
Seq('VAIVMGR')
Now using NCBI table 2, where TGA is not a stop codon:
>>> coding_dna.translate(table=2)
Seq('VAIVMGRWKGAR*')
>>> coding_dna.translate(table=2, to_stop=True)
Seq('VAIVMGRWKGAR')
In fact, GTG is an alternative start codon under NCBI table 2, meaning
this sequence could be a complete CDS:
>>> coding_dna.translate(table=2, cds=True)
Seq('MAIVMGRWKGAR')
It isn't a valid CDS under NCBI table 1, due to both the start codon
and also the in frame stop codons:
>>> coding_dna.translate(table=1, cds=True)
Traceback (most recent call last):
...
Bio.Data.CodonTable.TranslationError: First codon 'GTG' is not a start codon
If the sequence has no in-frame stop codon, then the to_stop argument
has no effect:
>>> coding_dna2 = Seq("TTGGCCATTGTAATGGGCCGC")
>>> coding_dna2.translate()
Seq('LAIVMGR')
>>> coding_dna2.translate(to_stop=True)
Seq('LAIVMGR')
NOTE - Ambiguous codons like "TAN" or "NNN" could be an amino acid
or a stop codon. These are translated as "X". Any invalid codon
(e.g. "TA?" or "T-A") will throw a TranslationError.
NOTE - This does NOT behave like the python string's translate
method. For that use str(my_seq).translate(...) instead
"""
try:
data = str(self)
except UndefinedSequenceError:
# translating an undefined sequence yields an undefined
# sequence with the length divided by 3
n = len(self)
if n % 3 != 0:
warnings.warn(
"Partial codon, len(sequence) not a multiple of three. "
"This may become an error in future.",
BiopythonWarning,
)
return Seq(None, n // 3)
return self.__class__(
_translate_str(str(self), table, stop_symbol, to_stop, cds, gap=gap)
)
def complement(self, inplace=None):
"""Return the complement as a DNA sequence.
>>> Seq("CGA").complement()
Seq('GCT')
Any U in the sequence is treated as a T:
>>> Seq("CGAUT").complement(inplace=False)
Seq('GCTAA')
In contrast, ``complement_rna`` returns an RNA sequence:
>>> Seq("CGAUT").complement_rna()
Seq('GCUAA')
The sequence is modified in-place and returned if inplace is True:
>>> my_seq = MutableSeq("CGA")
>>> my_seq
MutableSeq('CGA')
>>> my_seq.complement(inplace=False)
MutableSeq('GCT')
>>> my_seq
MutableSeq('CGA')
>>> my_seq.complement(inplace=True)
MutableSeq('GCT')
>>> my_seq
MutableSeq('GCT')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``complement_rna`` is called on a ``Seq`` object with ``inplace=True``.
"""
ttable = _dna_complement_table
try:
if inplace is None:
# deprecated
if isinstance(self._data, bytearray): # MutableSeq
warnings.warn(
"mutable_seq.complement() will change in the near "
"future and will no longer change the sequence in-"
"place by default. Please use\n"
"\n"
"mutable_seq.complement(inplace=True)\n"
"\n"
"if you want to continue to use this method to change "
"a mutable sequence in-place.",
BiopythonDeprecationWarning,
)
inplace = True
if isinstance(self._data, _PartiallyDefinedSequenceData):
for seq in self._data._data.values():
if b"U" in seq or b"u" in seq:
warnings.warn(
"seq.complement() will change in the near "
"future to always return DNA nucleotides only. "
"Please use\n"
"\n"
"seq.complement_rna()\n"
"\n"
"if you want to receive an RNA sequence instead.",
BiopythonDeprecationWarning,
)
for seq in self._data._data.values():
if b"t" in seq or b"T" in seq:
raise ValueError("Mixed RNA/DNA found")
ttable = _rna_complement_table
break
elif b"U" in self._data or b"u" in self._data:
warnings.warn(
"seq.complement() will change in the near future to "
"always return DNA nucleotides only. "
"Please use\n"
"\n"
"seq.complement_rna()\n"
"\n"
"if you want to receive an RNA sequence instead.",
BiopythonDeprecationWarning,
)
if b"t" in self._data or b"T" in self._data:
raise ValueError("Mixed RNA/DNA found")
ttable = _rna_complement_table
data = self._data.translate(ttable)
except UndefinedSequenceError:
# complement of an undefined sequence is an undefined sequence
# of the same length
return self
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[:] = data
return self
return self.__class__(data)
def complement_rna(self, inplace=False):
"""Return the complement as an RNA sequence.
>>> Seq("CGA").complement_rna()
Seq('GCU')
Any T in the sequence is treated as a U:
>>> Seq("CGAUT").complement_rna()
Seq('GCUAA')
In contrast, ``complement`` returns a DNA sequence by default:
>>> Seq("CGA").complement()
Seq('GCT')
The sequence is modified in-place and returned if inplace is True:
>>> my_seq = MutableSeq("CGA")
>>> my_seq
MutableSeq('CGA')
>>> my_seq.complement_rna()
MutableSeq('GCU')
>>> my_seq
MutableSeq('CGA')
>>> my_seq.complement_rna(inplace=True)
MutableSeq('GCU')
>>> my_seq
MutableSeq('GCU')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``complement_rna`` is called on a ``Seq`` object with ``inplace=True``.
"""
try:
data = self._data.translate(_rna_complement_table)
except UndefinedSequenceError:
# complement of an undefined sequence is an undefined sequence
# of the same length
return self
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[:] = data
return self
return self.__class__(data)
def reverse_complement(self, inplace=None):
"""Return the reverse complement as a DNA sequence.
>>> Seq("CGA").reverse_complement(inplace=False)
Seq('TCG')
Any U in the sequence is treated as a T:
>>> Seq("CGAUT").reverse_complement(inplace=False)
Seq('AATCG')
In contrast, ``reverse_complement_rna`` returns an RNA sequence:
>>> Seq("CGA").reverse_complement_rna()
Seq('UCG')
The sequence is modified in-place and returned if inplace is True:
>>> my_seq = MutableSeq("CGA")
>>> my_seq
MutableSeq('CGA')
>>> my_seq.reverse_complement(inplace=False)
MutableSeq('TCG')
>>> my_seq
MutableSeq('CGA')
>>> my_seq.reverse_complement(inplace=True)
MutableSeq('TCG')
>>> my_seq
MutableSeq('TCG')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``reverse_complement`` is called on a ``Seq`` object with
``inplace=True``.
"""
try:
if inplace is None:
# deprecated
if isinstance(self._data, bytearray): # MutableSeq
warnings.warn(
"mutable_seq.reverse_complement() will change in the "
"near future and will no longer change the sequence in-"
"place by default. Please use\n"
"\n"
"mutable_seq.reverse_complement(inplace=True)\n"
"\n"
"if you want to continue to use this method to change "
"a mutable sequence in-place.",
BiopythonDeprecationWarning,
)
inplace = True
else:
inplace = False
if isinstance(self._data, _PartiallyDefinedSequenceData):
for seq in self._data._data.values():
if b"U" in seq or b"u" in seq:
warnings.warn(
"seq.reverse_complement() will change in the near "
"future to always return DNA nucleotides only. "
"Please use\n"
"\n"
"seq.reverse_complement_rna()\n"
"\n"
"if you want to receive an RNA sequence instead.",
BiopythonDeprecationWarning,
)
for seq in self._data._data.values():
if b"t" in seq or b"T" in seq:
raise ValueError("Mixed RNA/DNA found")
return self.reverse_complement_rna(inplace=inplace)
elif b"U" in self._data or b"u" in self._data:
warnings.warn(
"seq.reverse_complement() will change in the near "
"future to always return DNA nucleotides only. "
"Please use\n"
"\n"
"seq.reverse_complement_rna()\n"
"\n"
"if you want to receive an RNA sequence instead.",
BiopythonDeprecationWarning,
)
if b"t" in self._data or b"T" in self._data:
raise ValueError("Mixed RNA/DNA found")
return self.reverse_complement_rna(inplace=inplace)
data = self._data.translate(_dna_complement_table)
except UndefinedSequenceError:
# reverse complement of an undefined sequence is an undefined sequence
# of the same length
return self
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[::-1] = data
return self
return self.__class__(data[::-1])
def reverse_complement_rna(self, inplace=False):
"""Return the reverse complement as an RNA sequence.
>>> Seq("CGA").reverse_complement_rna()
Seq('UCG')
Any T in the sequence is treated as a U:
>>> Seq("CGAUT").reverse_complement_rna()
Seq('AAUCG')
In contrast, ``reverse_complement`` returns a DNA sequence:
>>> Seq("CGA").reverse_complement(inplace=False)
Seq('TCG')
The sequence is modified in-place and returned if inplace is True:
>>> my_seq = MutableSeq("CGA")
>>> my_seq
MutableSeq('CGA')
>>> my_seq.reverse_complement_rna()
MutableSeq('UCG')
>>> my_seq
MutableSeq('CGA')
>>> my_seq.reverse_complement_rna(inplace=True)
MutableSeq('UCG')
>>> my_seq
MutableSeq('UCG')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``reverse_complement_rna`` is called on a ``Seq`` object with
``inplace=True``.
"""
try:
data = self._data.translate(_rna_complement_table)
except UndefinedSequenceError:
# reverse complement of an undefined sequence is an undefined sequence
# of the same length
return self
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[::-1] = data
return self
return self.__class__(data[::-1])
def transcribe(self, inplace=False):
"""Transcribe a DNA sequence into RNA and return the RNA sequence as a new Seq object.
>>> from Bio.Seq import Seq
>>> coding_dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG")
>>> coding_dna
Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG')
>>> coding_dna.transcribe()
Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG')
The sequence is modified in-place and returned if inplace is True:
>>> sequence = MutableSeq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG")
>>> sequence
MutableSeq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG')
>>> sequence.transcribe()
MutableSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG')
>>> sequence
MutableSeq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG')
>>> sequence.transcribe(inplace=True)
MutableSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG')
>>> sequence
MutableSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``transcribe`` is called on a ``Seq`` object with ``inplace=True``.
Trying to transcribe an RNA sequence has no effect.
If you have a nucleotide sequence which might be DNA or RNA
(or even a mixture), calling the transcribe method will ensure
any T becomes U.
Trying to transcribe a protein sequence will replace any
T for Threonine with U for Selenocysteine, which has no
biologically plausible rational.
>>> from Bio.Seq import Seq
>>> my_protein = Seq("MAIVMGRT")
>>> my_protein.transcribe()
Seq('MAIVMGRU')
"""
data = self._data.replace(b"T", b"U").replace(b"t", b"u")
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[:] = data
return self
return self.__class__(data)
def back_transcribe(self, inplace=False):
"""Return the DNA sequence from an RNA sequence by creating a new Seq object.
>>> from Bio.Seq import Seq
>>> messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG")
>>> messenger_rna
Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG')
>>> messenger_rna.back_transcribe()
Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG')
The sequence is modified in-place and returned if inplace is True:
>>> sequence = MutableSeq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG")
>>> sequence
MutableSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG')
>>> sequence.back_transcribe()
MutableSeq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG')
>>> sequence
MutableSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG')
>>> sequence.back_transcribe(inplace=True)
MutableSeq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG')
>>> sequence
MutableSeq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``transcribe`` is called on a ``Seq`` object with ``inplace=True``.
Trying to back-transcribe DNA has no effect, If you have a nucleotide
sequence which might be DNA or RNA (or even a mixture), calling the
back-transcribe method will ensure any U becomes T.
Trying to back-transcribe a protein sequence will replace any U for
Selenocysteine with T for Threonine, which is biologically meaningless.
>>> from Bio.Seq import Seq
>>> my_protein = Seq("MAIVMGRU")
>>> my_protein.back_transcribe()
Seq('MAIVMGRT')
"""
data = self._data.replace(b"U", b"T").replace(b"u", b"t")
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[:] = data
return self
return self.__class__(data)
def join(self, other):
"""Return a merge of the sequences in other, spaced by the sequence from self.
Accepts a Seq object, MutableSeq object, or string (and iterates over
the letters), or an iterable containing Seq, MutableSeq, or string
objects. These arguments will be concatenated with the calling sequence
as the spacer:
>>> concatenated = Seq('NNNNN').join([Seq("AAA"), Seq("TTT"), Seq("PPP")])
>>> concatenated
Seq('AAANNNNNTTTNNNNNPPP')
Joining the letters of a single sequence:
>>> Seq('NNNNN').join(Seq("ACGT"))
Seq('ANNNNNCNNNNNGNNNNNT')
>>> Seq('NNNNN').join("ACGT")
Seq('ANNNNNCNNNNNGNNNNNT')
"""
if isinstance(other, _SeqAbstractBaseClass):
return self.__class__(str(self).join(str(other)))
elif isinstance(other, str):
return self.__class__(str(self).join(other))
from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports
if isinstance(other, SeqRecord):
raise TypeError("Iterable cannot be a SeqRecord")
for c in other:
if isinstance(c, SeqRecord):
raise TypeError("Iterable cannot contain SeqRecords")
elif not isinstance(c, (str, _SeqAbstractBaseClass)):
raise TypeError(
"Input must be an iterable of Seq objects, MutableSeq objects, or strings"
)
return self.__class__(str(self).join([str(_) for _ in other]))
def replace(self, old, new, inplace=False):
"""Return a copy with all occurrences of subsequence old replaced by new.
>>> s = Seq("ACGTAACCGGTT")
>>> t = s.replace("AC", "XYZ")
>>> s
Seq('ACGTAACCGGTT')
>>> t
Seq('XYZGTAXYZCGGTT')
For mutable sequences, passing inplace=True will modify the sequence in place:
>>> m = MutableSeq("ACGTAACCGGTT")
>>> t = m.replace("AC", "XYZ")
>>> m
MutableSeq('ACGTAACCGGTT')
>>> t
MutableSeq('XYZGTAXYZCGGTT')
>>> m = MutableSeq("ACGTAACCGGTT")
>>> t = m.replace("AC", "XYZ", inplace=True)
>>> m
MutableSeq('XYZGTAXYZCGGTT')
>>> t
MutableSeq('XYZGTAXYZCGGTT')
As ``Seq`` objects are immutable, a ``TypeError`` is raised if
``replace`` is called on a ``Seq`` object with ``inplace=True``.
"""
if isinstance(old, _SeqAbstractBaseClass):
old = bytes(old)
elif isinstance(old, str):
old = old.encode("ASCII")
if isinstance(new, _SeqAbstractBaseClass):
new = bytes(new)
elif isinstance(new, str):
new = new.encode("ASCII")
data = self._data.replace(old, new)
if inplace:
if not isinstance(self._data, bytearray):
raise TypeError("Sequence is immutable")
self._data[:] = data
return self
return self.__class__(data)
@property
def defined(self):
"""Return True if the sequence is defined, False if undefined or partially defined.
Zero-length sequences are always considered to be defined.
"""
if isinstance(self._data, (bytes, bytearray)):
return True
else:
return self._data.defined
@property
def defined_ranges(self):
"""Return a tuple of the ranges where the sequence contents is defined.
The return value has the format ((start1, end1), (start2, end2), ...).
"""
if isinstance(self._data, (bytes, bytearray)):
length = len(self)
if length > 0:
return ((0, length),)
else:
return ()
else:
return self._data.defined_ranges
class Seq(_SeqAbstractBaseClass):
"""Read-only sequence object (essentially a string with biological methods).
Like normal python strings, our basic sequence object is immutable.
This prevents you from doing my_seq[5] = "A" for example, but does allow
Seq objects to be used as dictionary keys.
The Seq object provides a number of string like methods (such as count,
find, split and strip).
The Seq object also provides some biological methods, such as complement,
reverse_complement, transcribe, back_transcribe and translate (which are
not applicable to protein sequences).
"""
def __init__(self, data, length=None):
"""Create a Seq object.
Arguments:
- data - Sequence, required (string)
- length - Sequence length, used only if data is None or a dictionary (integer)
You will typically use Bio.SeqIO to read in sequences from files as
SeqRecord objects, whose sequence will be exposed as a Seq object via
the seq property.
However, you can also create a Seq object directly:
>>> from Bio.Seq import Seq
>>> my_seq = Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF")
>>> my_seq
Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF')
>>> print(my_seq)
MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF
To create a Seq object with for a sequence of known length but
unknown sequence contents, use None for the data argument and pass
the sequence length for the length argument. Trying to access the
sequence contents of a Seq object created in this way will raise
an UndefinedSequenceError:
>>> my_undefined_sequence = Seq(None, 20)
>>> my_undefined_sequence
Seq(None, length=20)
>>> len(my_undefined_sequence)
20
>>> print(my_undefined_sequence)
Traceback (most recent call last):
...
Bio.Seq.UndefinedSequenceError: Sequence content is undefined
If the sequence contents is known for parts of the sequence only, use
a dictionary for the data argument to pass the known sequence segments:
>>> my_partially_defined_sequence = Seq({3: "ACGT"}, 10)
>>> my_partially_defined_sequence
Seq({3: 'ACGT'}, length=10)
>>> len(my_partially_defined_sequence)
10
>>> print(my_partially_defined_sequence)
Traceback (most recent call last):
...
Bio.Seq.UndefinedSequenceError: Sequence content is only partially defined
>>> my_partially_defined_sequence[3:7]
Seq('ACGT')
>>> print(my_partially_defined_sequence[3:7])
ACGT
"""
if data is None:
if length is None:
raise ValueError("length must not be None if data is None")
elif length == 0:
self._data = b""
elif length < 0:
raise ValueError("length must not be negative.")
else:
self._data = _UndefinedSequenceData(length)
elif isinstance(data, (bytes, SequenceDataAbstractBaseClass)):
self._data = data
elif isinstance(data, (bytearray, _SeqAbstractBaseClass)):
self._data = bytes(data)
elif isinstance(data, str):
self._data = bytes(data, encoding="ASCII")
elif isinstance(data, dict):
if length is None:
raise ValueError("length must not be None if data is a dictionary")
elif length == 0:
self._data = b""
elif length < 0:
raise ValueError("length must not be negative.")
else:
end = -1
starts = sorted(data.keys())
_data = {}
for start in starts:
seq = data[start]
if isinstance(seq, str):
seq = bytes(seq, encoding="ASCII")
else:
try:
seq = bytes(seq)
except Exception:
raise ValueError("Expected bytes-like objects or strings")
if start < end:
raise ValueError("Sequence data are overlapping.")
elif start == end:
_data[current] += seq # noqa: F821
else:
_data[start] = seq
current = start
end = start + len(seq)
if end > length:
raise ValueError(
"Provided sequence data extend beyond sequence length."
)
elif end == length and current == 0:
# sequence is fully defined
self._data = _data[current]
else:
self._data = _PartiallyDefinedSequenceData(length, _data)
else:
raise TypeError(
"data should be a string, bytes, bytearray, Seq, or MutableSeq object"
)
def __hash__(self):
"""Hash of the sequence as a string for comparison.
See Seq object comparison documentation (method ``__eq__`` in
particular) as this has changed in Biopython 1.65. Older versions
would hash on object identity.
"""
return hash(self._data)
def ungap(self, gap="-"):
"""Return a copy of the sequence without the gap character(s) (DEPRECATED).
The gap character now defaults to the minus sign, and can only
be specified via the method argument. This is no longer possible
via the sequence's alphabet (as was possible up to Biopython 1.77):
>>> from Bio.Seq import Seq
>>> my_dna = Seq("-ATA--TGAAAT-TTGAAAA")
>>> my_dna
Seq('-ATA--TGAAAT-TTGAAAA')
>>> my_dna.ungap("-")
Seq('ATATGAAATTTGAAAA')
This method is DEPRECATED; please use my_dna.replace(gap, "") instead.
"""
warnings.warn(
"""\
myseq.ungap(gap) is deprecated; please use myseq.replace(gap, "") instead.""",
BiopythonDeprecationWarning,
)
if not gap:
raise ValueError("Gap character required.")
elif len(gap) != 1 or not isinstance(gap, str):
raise ValueError(f"Unexpected gap character, {gap!r}")
return self.replace(gap, b"")
class MutableSeq(_SeqAbstractBaseClass):
"""An editable sequence object.
Unlike normal python strings and our basic sequence object (the Seq class)
which are immutable, the MutableSeq lets you edit the sequence in place.
However, this means you cannot use a MutableSeq object as a dictionary key.
>>> from Bio.Seq import MutableSeq
>>> my_seq = MutableSeq("ACTCGTCGTCG")
>>> my_seq
MutableSeq('ACTCGTCGTCG')
>>> my_seq[5]
'T'
>>> my_seq[5] = "A"
>>> my_seq
MutableSeq('ACTCGACGTCG')
>>> my_seq[5]
'A'
>>> my_seq[5:8] = "NNN"
>>> my_seq
MutableSeq('ACTCGNNNTCG')
>>> len(my_seq)
11
Note that the MutableSeq object does not support as many string-like
or biological methods as the Seq object.
"""
def __init__(self, data):
"""Create a MutableSeq object."""
if isinstance(data, bytearray):
self._data = data
elif isinstance(data, bytes):
self._data = bytearray(data)
elif isinstance(data, str):
self._data = bytearray(data, "ASCII")
elif isinstance(data, MutableSeq):
self._data = data._data[:] # Take a copy
elif isinstance(data, Seq):
# Make no assumptions about the Seq subclass internal storage
self._data = bytearray(bytes(data))
else:
raise TypeError(
"data should be a string, bytearray object, Seq object, or a "
"MutableSeq object"
)
def __setitem__(self, index, value):
"""Set a subsequence of single letter via value parameter.
>>> my_seq = MutableSeq('ACTCGACGTCG')
>>> my_seq[0] = 'T'
>>> my_seq
MutableSeq('TCTCGACGTCG')
"""
if isinstance(index, numbers.Integral):
# Replacing a single letter with a new string
self._data[index] = ord(value)
else:
# Replacing a sub-sequence
if isinstance(value, MutableSeq):
self._data[index] = value._data
elif isinstance(value, Seq):
self._data[index] = bytes(value)
elif isinstance(value, str):
self._data[index] = value.encode("ASCII")
else:
raise TypeError(f"received unexpected type '{type(value).__name__}'")
def __delitem__(self, index):
"""Delete a subsequence of single letter.
>>> my_seq = MutableSeq('ACTCGACGTCG')
>>> del my_seq[0]
>>> my_seq
MutableSeq('CTCGACGTCG')
"""
# Could be deleting a single letter, or a slice
del self._data[index]
def append(self, c):
"""Add a subsequence to the mutable sequence object.
>>> my_seq = MutableSeq('ACTCGACGTCG')
>>> my_seq.append('A')
>>> my_seq
MutableSeq('ACTCGACGTCGA')
No return value.
"""
self._data.append(ord(c.encode("ASCII")))
def insert(self, i, c):
"""Add a subsequence to the mutable sequence object at a given index.
>>> my_seq = MutableSeq('ACTCGACGTCG')
>>> my_seq.insert(0,'A')
>>> my_seq
MutableSeq('AACTCGACGTCG')
>>> my_seq.insert(8,'G')
>>> my_seq
MutableSeq('AACTCGACGGTCG')
No return value.
"""
self._data.insert(i, ord(c.encode("ASCII")))
def pop(self, i=(-1)):
"""Remove a subsequence of a single letter at given index.
>>> my_seq = MutableSeq('ACTCGACGTCG')
>>> my_seq.pop()
'G'
>>> my_seq
MutableSeq('ACTCGACGTC')
>>> my_seq.pop()
'C'
>>> my_seq
MutableSeq('ACTCGACGT')
Returns the last character of the sequence.
"""
c = self._data[i]
del self._data[i]
return chr(c)
def remove(self, item):
"""Remove a subsequence of a single letter from mutable sequence.
>>> my_seq = MutableSeq('ACTCGACGTCG')
>>> my_seq.remove('C')
>>> my_seq
MutableSeq('ATCGACGTCG')
>>> my_seq.remove('A')
>>> my_seq
MutableSeq('TCGACGTCG')
No return value.
"""
codepoint = ord(item)
try:
self._data.remove(codepoint)
except ValueError:
raise ValueError("value not found in MutableSeq") from None
def reverse(self):
"""Modify the mutable sequence to reverse itself.
No return value.
"""
self._data.reverse()
def extend(self, other):
"""Add a sequence to the original mutable sequence object.
>>> my_seq = MutableSeq('ACTCGACGTCG')
>>> my_seq.extend('A')
>>> my_seq
MutableSeq('ACTCGACGTCGA')
>>> my_seq.extend('TTT')
>>> my_seq
MutableSeq('ACTCGACGTCGATTT')
No return value.
"""
if isinstance(other, MutableSeq):
self._data.extend(other._data)
elif isinstance(other, Seq):
self._data.extend(bytes(other))
elif isinstance(other, str):
self._data.extend(other.encode("ASCII"))
else:
raise TypeError("expected a string, Seq or MutableSeq")
class UndefinedSequenceError(ValueError):
"""Sequence contents is undefined."""
class _UndefinedSequenceData(SequenceDataAbstractBaseClass):
"""Stores the length of a sequence with an undefined sequence contents (PRIVATE).
Objects of this class can be used to create a Seq object to represent
sequences with a known length, but an unknown sequence contents.
Calling __len__ returns the sequence length, calling __getitem__ raises an
UndefinedSequenceError except for requests of zero size, for which it
returns an empty bytes object.
"""
__slots__ = ("_length",)
def __init__(self, length):
"""Initialize the object with the sequence length.
The calling function is responsible for ensuring that the length is
greater than zero.
"""
self._length = length
super().__init__()
def __getitem__(self, key):
if isinstance(key, slice):
start, end, step = key.indices(self._length)
size = len(range(start, end, step))
if size == 0:
return b""
return _UndefinedSequenceData(size)
else:
raise UndefinedSequenceError("Sequence content is undefined")
def __len__(self):
return self._length
def __bytes__(self):
raise UndefinedSequenceError("Sequence content is undefined")
def __add__(self, other):
length = len(self) + len(other)
try:
other = bytes(other)
except UndefinedSequenceError:
if isinstance(other, _UndefinedSequenceData):
return _UndefinedSequenceData(length)
else:
return NotImplemented
# _PartiallyDefinedSequenceData.__radd__ will handle this
else:
data = {len(self): other}
return _PartiallyDefinedSequenceData(length, data)
def __radd__(self, other):
data = {0: bytes(other)}
length = len(other) + len(self)
return _PartiallyDefinedSequenceData(length, data)
def upper(self):
"""Return an upper case copy of the sequence."""
# An upper case copy of an undefined sequence is an undefined
# sequence of the same length
return _UndefinedSequenceData(self._length)
def lower(self):
"""Return a lower case copy of the sequence."""
# A lower case copy of an undefined sequence is an undefined
# sequence of the same length
return _UndefinedSequenceData(self._length)
def isupper(self):
"""Return True if all ASCII characters in data are uppercase.
If there are no cased characters, the method returns False.
"""
# Character case is irrelevant for an undefined sequence
raise UndefinedSequenceError("Sequence content is undefined")
def islower(self):
"""Return True if all ASCII characters in data are lowercase.
If there are no cased characters, the method returns False.
"""
# Character case is irrelevant for an undefined sequence
raise UndefinedSequenceError("Sequence content is undefined")
def replace(self, old, new):
"""Return a copy with all occurrences of substring old replaced by new."""
# Replacing substring old by new in an undefined sequence will result
# in an undefined sequence of the same length, if old and new have the
# number of characters.
if len(old) != len(new):
raise UndefinedSequenceError("Sequence content is undefined")
return _UndefinedSequenceData(self._length)
@property
def defined(self):
"""Return False, as the sequence is not defined and has a non-zero length."""
return False
@property
def defined_ranges(self):
"""Return a tuple of the ranges where the sequence contents is defined.
As the sequence contents of an _UndefinedSequenceData object is fully
undefined, the return value is always an empty tuple.
"""
return ()
class _PartiallyDefinedSequenceData(SequenceDataAbstractBaseClass):
"""Stores the length of a sequence with an undefined sequence contents (PRIVATE).
Objects of this class can be used to create a Seq object to represent
sequences with a known length, but with a sequence contents that is only
partially known.
Calling __len__ returns the sequence length, calling __getitem__ returns
the sequence contents if known, otherwise an UndefinedSequenceError is
raised.
"""
__slots__ = ("_length", "_data")
def __init__(self, length, data):
"""Initialize with the sequence length and defined sequence segments.
The calling function is responsible for ensuring that the length is
greater than zero.
"""
self._length = length
self._data = data
super().__init__()
def __getitem__(self, key):
if isinstance(key, slice):
start, end, step = key.indices(self._length)
size = len(range(start, end, step))
if size == 0:
return b""
data = {}
for s, d in self._data.items():
indices = range(-s, -s + self._length)[key]
e = indices.stop
if step > 0:
if e <= 0:
continue
if indices.start < 0:
s = indices.start % step
else:
s = indices.start
else: # step < 0
if e < 0:
e = None
end = len(d) - 1
if indices.start > end:
s = end + (indices.start - end) % step
else:
s = indices.start
if s < 0:
continue
start = (s - indices.start) // step
d = d[s:e:step]
if d:
data[start] = d
if len(data) == 0: # Fully undefined sequence
return _UndefinedSequenceData(size)
# merge adjacent sequence segments
end = -1
previous = None # not needed here, but it keeps flake happy
items = data.items()
data = {}
for start, seq in items:
if end == start:
data[previous] += seq
else:
data[start] = seq
previous = start
end = start + len(seq)
if len(data) == 1:
seq = data.get(0)
if seq is not None and len(seq) == size:
return seq # Fully defined sequence; return bytes
if step < 0:
# use this after we drop Python 3.7:
# data = {start: data[start] for start in reversed(data)}
# use this as long as we support Python 3.7:
data = {start: data[start] for start in reversed(list(data.keys()))}
return _PartiallyDefinedSequenceData(size, data)
elif self._length <= key:
raise IndexError("sequence index out of range")
else:
for start, seq in self._data.items():
if start <= key and key < start + len(seq):
return seq[key - start]
raise UndefinedSequenceError("Sequence at position %d is undefined" % key)
def __len__(self):
return self._length
def __bytes__(self):
raise UndefinedSequenceError("Sequence content is only partially defined")
def __add__(self, other):
length = len(self) + len(other)
data = dict(self._data)
items = list(self._data.items())
start, seq = items[-1]
end = start + len(seq)
try:
other = bytes(other)
except UndefinedSequenceError:
if isinstance(other, _UndefinedSequenceData):
pass
elif isinstance(other, _PartiallyDefinedSequenceData):
other_items = list(other._data.items())
if end == len(self):
other_start, other_seq = other_items.pop(0)
if other_start == 0:
data[start] += other_seq
else:
data[len(self) + other_start] = other_seq
for other_start, other_seq in other_items:
data[len(self) + other_start] = other_seq
else:
if end == len(self):
data[start] += other
else:
data[len(self)] = other
return _PartiallyDefinedSequenceData(length, data)
def __radd__(self, other):
length = len(other) + len(self)
try:
other = bytes(other)
except UndefinedSequenceError:
data = {len(other) + start: seq for start, seq in self._data.items()}
else:
data = {0: other}
items = list(self._data.items())
start, seq = items.pop(0)
if start == 0:
data[0] += seq
else:
data[len(other) + start] = seq
for start, seq in items:
data[len(other) + start] = seq
return _PartiallyDefinedSequenceData(length, data)
def __mul__(self, other):
length = self._length
items = self._data.items()
data = {}
end = -1
previous = None # not needed here, but it keeps flake happy
for i in range(other):
for start, seq in items:
start += i * length
if end == start:
data[previous] += seq
else:
data[start] = seq
previous = start
end = start + len(seq)
return _PartiallyDefinedSequenceData(length * other, data)
def upper(self):
"""Return an upper case copy of the sequence."""
data = {start: seq.upper() for start, seq in self._data.items()}
return _PartiallyDefinedSequenceData(self._length, data)
def lower(self):
"""Return a lower case copy of the sequence."""
data = {start: seq.lower() for start, seq in self._data.items()}
return _PartiallyDefinedSequenceData(self._length, data)
def isupper(self):
"""Return True if all ASCII characters in data are uppercase.
If there are no cased characters, the method returns False.
"""
# Character case is irrelevant for an undefined sequence
raise UndefinedSequenceError("Sequence content is only partially defined")
def islower(self):
"""Return True if all ASCII characters in data are lowercase.
If there are no cased characters, the method returns False.
"""
# Character case is irrelevant for an undefined sequence
raise UndefinedSequenceError("Sequence content is only partially defined")
def translate(self, table, delete=b""):
"""Return a copy with each character mapped by the given translation table.
table
Translation table, which must be a bytes object of length 256.
All characters occurring in the optional argument delete are removed.
The remaining characters are mapped through the given translation table.
"""
items = self._data.items()
data = {start: seq.translate(table, delete) for start, seq in items}
return _PartiallyDefinedSequenceData(self._length, data)
def replace(self, old, new):
"""Return a copy with all occurrences of substring old replaced by new."""
# Replacing substring old by new in the undefined sequence segments
# will result in an undefined sequence segment of the same length, if
# old and new have the number of characters. If not, an error is raised,
# as the correct start positions cannot be calculated reliably.
if len(old) != len(new):
raise UndefinedSequenceError(
"Sequence content is only partially defined; substring \n"
"replacement cannot be performed reliably"
)
items = self._data.items()
data = {start: seq.replace(old, new) for start, seq in items}
return _PartiallyDefinedSequenceData(self._length, data)
@property
def defined(self):
"""Return False, as the sequence is not fully defined and has a non-zero length."""
return False
@property
def defined_ranges(self):
"""Return a tuple of the ranges where the sequence contents is defined.
The return value has the format ((start1, end1), (start2, end2), ...).
"""
return tuple((start, start + len(seq)) for start, seq in self._data.items())
# The transcribe, backward_transcribe, and translate functions are
# user-friendly versions of the corresponding Seq/MutableSeq methods.
# The functions work both on Seq objects, and on strings.
def transcribe(dna):
"""Transcribe a DNA sequence into RNA.
If given a string, returns a new string object.
Given a Seq or MutableSeq, returns a new Seq object.
e.g.
>>> transcribe("ACTGN")
'ACUGN'
"""
if isinstance(dna, Seq):
return dna.transcribe()
elif isinstance(dna, MutableSeq):
return Seq(dna).transcribe()
else:
return dna.replace("T", "U").replace("t", "u")
def back_transcribe(rna):
"""Return the RNA sequence back-transcribed into DNA.
If given a string, returns a new string object.
Given a Seq or MutableSeq, returns a new Seq object.
e.g.
>>> back_transcribe("ACUGN")
'ACTGN'
"""
if isinstance(rna, Seq):
return rna.back_transcribe()
elif isinstance(rna, MutableSeq):
return Seq(rna).back_transcribe()
else:
return rna.replace("U", "T").replace("u", "t")
def _translate_str(
sequence, table, stop_symbol="*", to_stop=False, cds=False, pos_stop="X", gap=None
):
"""Translate nucleotide string into a protein string (PRIVATE).
Arguments:
- sequence - a string
- table - Which codon table to use? This can be either a name (string),
an NCBI identifier (integer), or a CodonTable object (useful for
non-standard genetic codes). This defaults to the "Standard" table.
- stop_symbol - a single character string, what to use for terminators.
- to_stop - boolean, should translation terminate at the first
in frame stop codon? If there is no in-frame stop codon
then translation continues to the end.
- pos_stop - a single character string for a possible stop codon
(e.g. TAN or NNN)
- cds - Boolean, indicates this is a complete CDS. If True, this
checks the sequence starts with a valid alternative start
codon (which will be translated as methionine, M), that the
sequence length is a multiple of three, and that there is a
single in frame stop codon at the end (this will be excluded
from the protein sequence, regardless of the to_stop option).
If these tests fail, an exception is raised.
- gap - Single character string to denote symbol used for gaps.
Defaults to None.
Returns a string.
e.g.
>>> from Bio.Data import CodonTable
>>> table = CodonTable.ambiguous_dna_by_id[1]
>>> _translate_str("AAA", table)
'K'
>>> _translate_str("TAR", table)
'*'
>>> _translate_str("TAN", table)
'X'
>>> _translate_str("TAN", table, pos_stop="@")
'@'
>>> _translate_str("TA?", table)
Traceback (most recent call last):
...
Bio.Data.CodonTable.TranslationError: Codon 'TA?' is invalid
In a change to older versions of Biopython, partial codons are now
always regarded as an error (previously only checked if cds=True)
and will trigger a warning (likely to become an exception in a
future release).
If **cds=True**, the start and stop codons are checked, and the start
codon will be translated at methionine. The sequence must be an
while number of codons.
>>> _translate_str("ATGCCCTAG", table, cds=True)
'MP'
>>> _translate_str("AAACCCTAG", table, cds=True)
Traceback (most recent call last):
...
Bio.Data.CodonTable.TranslationError: First codon 'AAA' is not a start codon
>>> _translate_str("ATGCCCTAGCCCTAG", table, cds=True)
Traceback (most recent call last):
...
Bio.Data.CodonTable.TranslationError: Extra in frame stop codon 'TAG' found.
"""
try:
table_id = int(table)
except ValueError:
# Assume it's a table name
# The same table can be used for RNA or DNA
try:
codon_table = CodonTable.ambiguous_generic_by_name[table]
except KeyError:
if isinstance(table, str):
raise ValueError(
"The Bio.Seq translate methods and function DO NOT "
"take a character string mapping table like the python "
"string object's translate method. "
"Use str(my_seq).translate(...) instead."
) from None
else:
raise TypeError("table argument must be integer or string") from None
except (AttributeError, TypeError):
# Assume it's a CodonTable object
if isinstance(table, CodonTable.CodonTable):
codon_table = table
else:
raise ValueError("Bad table argument") from None
else:
# Assume it's a table ID
# The same table can be used for RNA or DNA
codon_table = CodonTable.ambiguous_generic_by_id[table_id]
sequence = sequence.upper()
amino_acids = []
forward_table = codon_table.forward_table
stop_codons = codon_table.stop_codons
if codon_table.nucleotide_alphabet is not None:
valid_letters = set(codon_table.nucleotide_alphabet.upper())
else:
# Assume the worst case, ambiguous DNA or RNA:
valid_letters = set(
IUPACData.ambiguous_dna_letters.upper()
+ IUPACData.ambiguous_rna_letters.upper()
)
n = len(sequence)
# Check for tables with 'ambiguous' (dual-coding) stop codons:
dual_coding = [c for c in stop_codons if c in forward_table]
if dual_coding:
c = dual_coding[0]
if to_stop:
raise ValueError(
"You cannot use 'to_stop=True' with this table as it contains"
f" {len(dual_coding)} codon(s) which can be both STOP and an"
f" amino acid (e.g. '{c}' -> '{forward_table[c]}' or STOP)."
)
warnings.warn(
f"This table contains {len(dual_coding)} codon(s) which code(s) for"
f" both STOP and an amino acid (e.g. '{c}' -> '{forward_table[c]}'"
" or STOP). Such codons will be translated as amino acid.",
BiopythonWarning,
)
if cds:
if str(sequence[:3]).upper() not in codon_table.start_codons:
raise CodonTable.TranslationError(
f"First codon '{sequence[:3]}' is not a start codon"
)
if n % 3 != 0:
raise CodonTable.TranslationError(
f"Sequence length {n} is not a multiple of three"
)
if str(sequence[-3:]).upper() not in stop_codons:
raise CodonTable.TranslationError(
f"Final codon '{sequence[-3:]}' is not a stop codon"
)
# Don't translate the stop symbol, and manually translate the M
sequence = sequence[3:-3]
n -= 6
amino_acids = ["M"]
elif n % 3 != 0:
warnings.warn(
"Partial codon, len(sequence) not a multiple of three. "
"Explicitly trim the sequence or add trailing N before "
"translation. This may become an error in future.",
BiopythonWarning,
)
if gap is not None:
if not isinstance(gap, str):
raise TypeError("Gap character should be a single character string.")
elif len(gap) > 1:
raise ValueError("Gap character should be a single character string.")
for i in range(0, n - n % 3, 3):
codon = sequence[i : i + 3]
try:
amino_acids.append(forward_table[codon])
except (KeyError, CodonTable.TranslationError):
if codon in codon_table.stop_codons:
if cds:
raise CodonTable.TranslationError(
f"Extra in frame stop codon '{codon}' found."
) from None
if to_stop:
break
amino_acids.append(stop_symbol)
elif valid_letters.issuperset(set(codon)):
# Possible stop codon (e.g. NNN or TAN)
amino_acids.append(pos_stop)
elif gap is not None and codon == gap * 3:
# Gapped translation
amino_acids.append(gap)
else:
raise CodonTable.TranslationError(
f"Codon '{codon}' is invalid"
) from None
return "".join(amino_acids)
def translate(
sequence, table="Standard", stop_symbol="*", to_stop=False, cds=False, gap=None
):
"""Translate a nucleotide sequence into amino acids.
If given a string, returns a new string object. Given a Seq or
MutableSeq, returns a Seq object.
Arguments:
- table - Which codon table to use? This can be either a name
(string), an NCBI identifier (integer), or a CodonTable object
(useful for non-standard genetic codes). Defaults to the "Standard"
table.
- stop_symbol - Single character string, what to use for any
terminators, defaults to the asterisk, "*".
- to_stop - Boolean, defaults to False meaning do a full
translation continuing on past any stop codons
(translated as the specified stop_symbol). If
True, translation is terminated at the first in
frame stop codon (and the stop_symbol is not
appended to the returned protein sequence).
- cds - Boolean, indicates this is a complete CDS. If True, this
checks the sequence starts with a valid alternative start
codon (which will be translated as methionine, M), that the
sequence length is a multiple of three, and that there is a
single in frame stop codon at the end (this will be excluded
from the protein sequence, regardless of the to_stop option).
If these tests fail, an exception is raised.
- gap - Single character string to denote symbol used for gaps.
Defaults to None.
A simple string example using the default (standard) genetic code:
>>> coding_dna = "GTGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG"
>>> translate(coding_dna)
'VAIVMGR*KGAR*'
>>> translate(coding_dna, stop_symbol="@")
'VAIVMGR@KGAR@'
>>> translate(coding_dna, to_stop=True)
'VAIVMGR'
Now using NCBI table 2, where TGA is not a stop codon:
>>> translate(coding_dna, table=2)
'VAIVMGRWKGAR*'
>>> translate(coding_dna, table=2, to_stop=True)
'VAIVMGRWKGAR'
In fact this example uses an alternative start codon valid under NCBI
table 2, GTG, which means this example is a complete valid CDS which
when translated should really start with methionine (not valine):
>>> translate(coding_dna, table=2, cds=True)
'MAIVMGRWKGAR'
Note that if the sequence has no in-frame stop codon, then the to_stop
argument has no effect:
>>> coding_dna2 = "GTGGCCATTGTAATGGGCCGC"
>>> translate(coding_dna2)
'VAIVMGR'
>>> translate(coding_dna2, to_stop=True)
'VAIVMGR'
NOTE - Ambiguous codons like "TAN" or "NNN" could be an amino acid
or a stop codon. These are translated as "X". Any invalid codon
(e.g. "TA?" or "T-A") will throw a TranslationError.
It will however translate either DNA or RNA.
NOTE - Since version 1.71 Biopython contains codon tables with 'ambiguous
stop codons'. These are stop codons with unambiguous sequence but which
have a context dependent coding as STOP or as amino acid. With these tables
'to_stop' must be False (otherwise a ValueError is raised). The dual
coding codons will always be translated as amino acid, except for
'cds=True', where the last codon will be translated as STOP.
>>> coding_dna3 = "ATGGCACGGAAGTGA"
>>> translate(coding_dna3)
'MARK*'
>>> translate(coding_dna3, table=27) # Table 27: TGA -> STOP or W
'MARKW'
It will however raise a BiopythonWarning (not shown).
>>> translate(coding_dna3, table=27, cds=True)
'MARK'
>>> translate(coding_dna3, table=27, to_stop=True)
Traceback (most recent call last):
...
ValueError: You cannot use 'to_stop=True' with this table ...
"""
if isinstance(sequence, Seq):
return sequence.translate(table, stop_symbol, to_stop, cds)
elif isinstance(sequence, MutableSeq):
# Return a Seq object
return Seq(sequence).translate(table, stop_symbol, to_stop, cds)
else:
# Assume it's a string, return a string
return _translate_str(sequence, table, stop_symbol, to_stop, cds, gap=gap)
def reverse_complement(sequence, inplace=None):
"""Return the reverse complement as a DNA sequence.
If given a string, returns a new string object.
Given a Seq object, returns a new Seq object.
Given a MutableSeq, returns a new MutableSeq object.
Given a SeqRecord object, returns a new SeqRecord object.
>>> my_seq = "CGA"
>>> reverse_complement(my_seq, inplace=False)
'TCG'
>>> my_seq = Seq("CGA")
>>> reverse_complement(my_seq, inplace=False)
Seq('TCG')
>>> my_seq = MutableSeq("CGA")
>>> reverse_complement(my_seq, inplace=False)
MutableSeq('TCG')
>>> my_seq
MutableSeq('CGA')
Any U in the sequence is treated as a T:
>>> reverse_complement(Seq("CGAUT"), inplace=False)
Seq('AATCG')
In contrast, ``reverse_complement_rna`` returns an RNA sequence:
>>> reverse_complement_rna(Seq("CGAUT"))
Seq('AAUCG')
Supports and lower- and upper-case characters, and unambiguous and
ambiguous nucleotides. All other characters are not converted:
>>> reverse_complement("ACGTUacgtuXYZxyz", inplace=False)
'zrxZRXaacgtAACGT'
The sequence is modified in-place and returned if inplace is True:
>>> my_seq = MutableSeq("CGA")
>>> reverse_complement(my_seq, inplace=True)
MutableSeq('TCG')
>>> my_seq
MutableSeq('TCG')
As strings and ``Seq`` objects are immutable, a ``TypeError`` is
raised if ``reverse_complement`` is called on a ``Seq`` object with
``inplace=True``.
"""
from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports
if inplace is None:
# deprecated
if isinstance(sequence, Seq):
if b"U" in sequence._data or b"u" in sequence._data:
warnings.warn(
"reverse_complement(sequence) will change in the "
"near future to always return DNA nucleotides only. "
"Please use\n"
"\n"
"reverse_complement_rna(sequence)\n"
"\n"
"if you want to receive an RNA sequence instead.",
BiopythonDeprecationWarning,
)
if b"T" in sequence._data or b"t" in sequence._data:
raise ValueError("Mixed RNA/DNA found")
return sequence.reverse_complement_rna()
elif isinstance(sequence, MutableSeq):
# Return a Seq
# Don't use the MutableSeq reverse_complement method as it is
# 'in place'.
warnings.warn(
"reverse_complement(mutable_seq) will change in the near "
"future to return a MutableSeq object instead of a Seq object.",
BiopythonDeprecationWarning,
)
return Seq(sequence).reverse_complement()
else: # str
if "U" in sequence or "u" in sequence:
warnings.warn(
"reverse_complement(sequence) will change in the "
"near future to always return DNA nucleotides only. "
"Please use\n"
"\n"
"reverse_complement_rna(sequence)\n"
"\n"
"if you want to receive an RNA sequence instead.",
BiopythonDeprecationWarning,
)
if "T" in sequence or "t" in sequence:
raise ValueError("Mixed RNA/DNA found")
sequence = sequence.encode("ASCII")
sequence = sequence.translate(_rna_complement_table)
return sequence.decode("ASCII")[::-1]
if isinstance(sequence, (Seq, MutableSeq)):
return sequence.reverse_complement(inplace)
if isinstance(sequence, SeqRecord):
if inplace:
raise TypeError("SeqRecords are immutable")
return sequence.reverse_complement()
# Assume it's a string.
if inplace:
raise TypeError("strings are immutable")
sequence = sequence.encode("ASCII")
sequence = sequence.translate(_dna_complement_table)
sequence = sequence.decode("ASCII")
return sequence[::-1]
def reverse_complement_rna(sequence, inplace=False):
"""Return the reverse complement as an RNA sequence.
If given a string, returns a new string object.
Given a Seq object, returns a new Seq object.
Given a MutableSeq, returns a new MutableSeq object.
Given a SeqRecord object, returns a new SeqRecord object.
>>> my_seq = "CGA"
>>> reverse_complement_rna(my_seq)
'UCG'
>>> my_seq = Seq("CGA")
>>> reverse_complement_rna(my_seq)
Seq('UCG')
>>> my_seq = MutableSeq("CGA")
>>> reverse_complement_rna(my_seq)
MutableSeq('UCG')
>>> my_seq
MutableSeq('CGA')
Any T in the sequence is treated as a U:
>>> reverse_complement_rna(Seq("CGAUT"))
Seq('AAUCG')
In contrast, ``reverse_complement`` returns a DNA sequence:
>>> reverse_complement(Seq("CGAUT"), inplace=False)
Seq('AATCG')
Supports and lower- and upper-case characters, and unambiguous and
ambiguous nucleotides. All other characters are not converted:
>>> reverse_complement_rna("ACGTUacgtuXYZxyz")
'zrxZRXaacguAACGU'
The sequence is modified in-place and returned if inplace is True:
>>> my_seq = MutableSeq("CGA")
>>> reverse_complement_rna(my_seq, inplace=True)
MutableSeq('UCG')
>>> my_seq
MutableSeq('UCG')
As strings and ``Seq`` objects are immutable, a ``TypeError`` is
raised if ``reverse_complement`` is called on a ``Seq`` object with
``inplace=True``.
"""
from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports
if isinstance(sequence, (Seq, MutableSeq)):
return sequence.reverse_complement_rna(inplace)
if isinstance(sequence, SeqRecord):
if inplace:
raise TypeError("SeqRecords are immutable")
return sequence.reverse_complement_rna()
# Assume it's a string.
if inplace:
raise TypeError("strings are immutable")
sequence = sequence.encode("ASCII")
sequence = sequence.translate(_rna_complement_table)
sequence = sequence.decode("ASCII")
return sequence[::-1]
def complement(sequence, inplace=None):
"""Return the complement as a DNA sequence.
If given a string, returns a new string object.
Given a Seq object, returns a new Seq object.
Given a MutableSeq, returns a new MutableSeq object.
Given a SeqRecord object, returns a new SeqRecord object.
>>> my_seq = "CGA"
>>> complement(my_seq, inplace=False)
'GCT'
>>> my_seq = Seq("CGA")
>>> complement(my_seq, inplace=False)
Seq('GCT')
>>> my_seq = MutableSeq("CGA")
>>> complement(my_seq, inplace=False)
MutableSeq('GCT')
>>> my_seq
MutableSeq('CGA')
Any U in the sequence is treated as a T:
>>> complement(Seq("CGAUT"), inplace=False)
Seq('GCTAA')
In contrast, ``complement_rna`` returns an RNA sequence:
>>> complement_rna(Seq("CGAUT"))
Seq('GCUAA')
Supports and lower- and upper-case characters, and unambiguous and
ambiguous nucleotides. All other characters are not converted:
>>> complement("ACGTUacgtuXYZxyz", inplace=False)
'TGCAAtgcaaXRZxrz'
The sequence is modified in-place and returned if inplace is True:
>>> my_seq = MutableSeq("CGA")
>>> complement(my_seq, inplace=True)
MutableSeq('GCT')
>>> my_seq
MutableSeq('GCT')
As strings and ``Seq`` objects are immutable, a ``TypeError`` is
raised if ``reverse_complement`` is called on a ``Seq`` object with
``inplace=True``.
"""
from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports
if inplace is None:
# deprecated
if isinstance(sequence, Seq):
# Return a Seq
if b"U" in sequence._data or b"u" in sequence._data:
warnings.warn(
"complement(sequence) will change in the near "
"future to always return DNA nucleotides only. "
"Please use\n"
"\n"
"complement_rna(sequence)\n"
"\n"
"if you want to receive an RNA sequence instead.",
BiopythonDeprecationWarning,
)
if b"T" in sequence._data or b"t" in sequence._data:
raise ValueError("Mixed RNA/DNA found")
return sequence.complement_rna()
elif isinstance(sequence, MutableSeq):
# Return a Seq
# Don't use the MutableSeq reverse_complement method as it is
# 'in place'.
warnings.warn(
"complement(mutable_seq) will change in the near future"
"to return a MutableSeq object instead of a Seq object.",
BiopythonDeprecationWarning,
)
return Seq(sequence).complement()
else:
if "U" in sequence or "u" in sequence:
warnings.warn(
"complement(sequence) will change in the near "
"future to always return DNA nucleotides only. "
"Please use\n"
"\n"
"complement_rna(sequence)\n"
"\n"
"if you want to receive an RNA sequence instead.",
BiopythonDeprecationWarning,
)
if "T" in sequence or "t" in sequence:
raise ValueError("Mixed RNA/DNA found")
ttable = _rna_complement_table
sequence = sequence.encode("ASCII")
sequence = sequence.translate(ttable)
return sequence.decode("ASCII")
if isinstance(sequence, (Seq, MutableSeq)):
return sequence.complement(inplace)
if isinstance(sequence, SeqRecord):
if inplace:
raise TypeError("SeqRecords are immutable")
return sequence.complement()
# Assume it's a string.
if inplace:
raise TypeError("strings are immutable")
sequence = sequence.encode("ASCII")
sequence = sequence.translate(_dna_complement_table)
return sequence.decode("ASCII")
def complement_rna(sequence, inplace=False):
"""Return the complement as an RNA sequence.
If given a string, returns a new string object.
Given a Seq object, returns a new Seq object.
Given a MutableSeq, returns a new MutableSeq object.
Given a SeqRecord object, returns a new SeqRecord object.
>>> my_seq = "CGA"
>>> complement_rna(my_seq)
'GCU'
>>> my_seq = Seq("CGA")
>>> complement_rna(my_seq)
Seq('GCU')
>>> my_seq = MutableSeq("CGA")
>>> complement_rna(my_seq)
MutableSeq('GCU')
>>> my_seq
MutableSeq('CGA')
Any T in the sequence is treated as a U:
>>> complement_rna(Seq("CGAUT"))
Seq('GCUAA')
In contrast, ``complement`` returns a DNA sequence:
>>> complement(Seq("CGAUT"),inplace=False)
Seq('GCTAA')
Supports and lower- and upper-case characters, and unambiguous and
ambiguous nucleotides. All other characters are not converted:
>>> complement_rna("ACGTUacgtuXYZxyz")
'UGCAAugcaaXRZxrz'
The sequence is modified in-place and returned if inplace is True:
>>> my_seq = MutableSeq("CGA")
>>> complement(my_seq, inplace=True)
MutableSeq('GCT')
>>> my_seq
MutableSeq('GCT')
As strings and ``Seq`` objects are immutable, a ``TypeError`` is
raised if ``reverse_complement`` is called on a ``Seq`` object with
``inplace=True``.
"""
from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports
if isinstance(sequence, (Seq, MutableSeq)):
return sequence.complement_rna(inplace)
if isinstance(sequence, SeqRecord):
if inplace:
raise TypeError("SeqRecords are immutable")
return sequence.complement_rna()
# Assume it's a string.
if inplace:
raise TypeError("strings are immutable")
sequence = sequence.encode("ASCII")
sequence = sequence.translate(_rna_complement_table)
return sequence.decode("ASCII")
def _test():
"""Run the Bio.Seq module's doctests (PRIVATE)."""
print("Running doctests...")
import doctest
doctest.testmod(optionflags=doctest.IGNORE_EXCEPTION_DETAIL)
print("Done")
if __name__ == "__main__":
_test()
|