File: Restriction.py

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

"""Restriction Enzyme classes.

Notes about the diverses class of the restriction enzyme implementation::

            RestrictionType is the type of all restriction enzymes.
        ----------------------------------------------------------------------------
            AbstractCut implements some methods that are common to all enzymes.
        ----------------------------------------------------------------------------
            NoCut, OneCut,TwoCuts   represent the number of double strand cuts
                                    produced by the enzyme.
                                    they correspond to the 4th field of the
                                    rebase record emboss_e.NNN.
                    0->NoCut    : the enzyme is not characterised.
                    2->OneCut   : the enzyme produce one double strand cut.
                    4->TwoCuts  : two double strand cuts.
        ----------------------------------------------------------------------------
            Meth_Dep, Meth_Undep    represent the methylation susceptibility to
                                    the enzyme.
                                    Not implemented yet.
        ----------------------------------------------------------------------------
            Palindromic,            if the site is palindromic or not.
            NotPalindromic          allow some optimisations of the code.
                                    No need to check the reverse strand
                                    with palindromic sites.
        ----------------------------------------------------------------------------
            Unknown, Blunt,         represent the overhang.
            Ov5, Ov3                Unknown is here for symmetry reasons and
                                    correspond to enzymes that are not
                                    characterised in rebase.
        ----------------------------------------------------------------------------
            Defined, Ambiguous,     represent the sequence of the overhang.
            NotDefined
                                    NotDefined is for enzymes not characterised
                                    in rebase.

                                    Defined correspond to enzymes that display
                                    a constant overhang whatever the sequence.
                                    ex : EcoRI. G^AATTC -> overhang :AATT
                                                CTTAA^G

                                    Ambiguous : the overhang varies with the
                                    sequence restricted.
                                    Typically enzymes which cut outside their
                                    restriction site or (but not always)
                                    inside an ambiguous site.
                                    ex:
                                    AcuI CTGAAG(22/20)  -> overhang : NN
                                    AasI GACNNN^NNNGTC  -> overhang : NN
                                         CTGN^NNNNNCAG

                note : these 3 classes refers to the overhang not the site.
                   So the enzyme ApoI (RAATTY) is defined even if its
                   restriction site is ambiguous.

                        ApoI R^AATTY -> overhang : AATT -> Defined
                             YTTAA^R
                   Accordingly, blunt enzymes are always Defined even
                   when they cut outside their restriction site.
        ----------------------------------------------------------------------------
            Not_available,          as found in rebase file emboss_r.NNN files.
            Commercially_available
                                    allow the selection of the enzymes
                                    according to their suppliers to reduce the
                                    quantity of results.
                                    Also will allow the implementation of
                                    buffer compatibility tables. Not
                                    implemented yet.

                                    the list of suppliers is extracted from
                                    emboss_s.NNN
        ----------------------------------------------------------------------------
"""

from __future__ import print_function
from Bio._py3k import zip
from Bio._py3k import filter
from Bio._py3k import range

import re
import itertools

from Bio.Seq import Seq, MutableSeq
from Bio.Alphabet import IUPAC

from Bio.Restriction.Restriction_Dictionary import rest_dict as enzymedict
from Bio.Restriction.Restriction_Dictionary import typedict
from Bio.Restriction.Restriction_Dictionary import suppliers as suppliers_dict
# TODO: Consider removing this wildcard import.
from Bio.Restriction.RanaConfig import *
from Bio.Restriction.PrintFormat import PrintFormat


# Used to use Bio.Restriction.DNAUtils.check_bases (and expose it under this
# namespace), but have deprecated that module.


def _check_bases(seq_string):
    """Check characters in a string (PRIVATE).

    Remove digits and white space present in string. Allows any valid ambiguous
    IUPAC DNA single letters codes (ABCDGHKMNRSTVWY, lower case are converted).

    Other characters (e.g. symbols) trigger a TypeError.

    Returns the string WITH A LEADING SPACE (!). This is for backwards
    compatibility, and may in part be explained by the fact that
    Bio.Restriction doesn't use zero based counting.
    """
    # Remove white space and make upper case:
    seq_string = "".join(seq_string.split()).upper()
    # Remove digits
    for c in "0123456789":
        seq_string = seq_string.replace(c, "")
    # Check only allowed IUPAC letters
    if not set(seq_string).issubset(set("ABCDGHKMNRSTVWY")):
        raise TypeError("Invalid character found in %s" % repr(seq_string))
    return " " + seq_string


matching = {'A': 'ARWMHVDN', 'C': 'CYSMHBVN', 'G': 'GRSKBVDN',
            'T': 'TYWKHBDN', 'R': 'ABDGHKMNSRWV', 'Y': 'CBDHKMNSTWVY',
            'W': 'ABDHKMNRTWVY', 'S': 'CBDGHKMNSRVY', 'M': 'ACBDHMNSRWVY',
            'K': 'BDGHKNSRTWVY', 'H': 'ACBDHKMNSRTWVY',
            'B': 'CBDGHKMNSRTWVY', 'V': 'ACBDGHKMNSRWVY',
            'D': 'ABDGHKMNSRTWVY', 'N': 'ACBDGHKMNSRTWVY'}

DNA = Seq


class FormattedSeq(object):
    """FormattedSeq(seq, [linear=True])-> new FormattedSeq.

    Translate a Bio.Seq into a formatted sequence to be used with Restriction.

    Roughly:
        remove anything which is not IUPAC alphabet and then add a space
        in front of the sequence to get a biological index instead of a
        python index (i.e. index of the first base is 1 not 0).

        Retains information about the shape of the molecule linear (default)
        or circular. Restriction sites are search over the edges of circular
        sequence.
        """

    def __init__(self, seq, linear=True):
        """FormattedSeq(seq, [linear=True])-> new FormattedSeq.

        seq is either a Bio.Seq, Bio.MutableSeq or a FormattedSeq.
        if seq is a FormattedSeq, linear will have no effect on the
        shape of the sequence.
        """
        if isinstance(seq, (Seq, MutableSeq)):
            stringy = str(seq)
            self.lower = stringy.islower()
            # Note this adds a leading space to the sequence (!)
            self.data = _check_bases(stringy)
            self.linear = linear
            self.klass = seq.__class__
            self.alphabet = seq.alphabet
        elif isinstance(seq, FormattedSeq):
            self.lower = seq.lower
            self.data = seq.data
            self.linear = seq.linear
            self.alphabet = seq.alphabet
            self.klass = seq.klass
        else:
            raise TypeError('expected Seq or MutableSeq, got %s' % type(seq))

    def __len__(self):
        return len(self.data) - 1

    def __repr__(self):
        return 'FormattedSeq(%s, linear=%s)' % (repr(self[1:]),
                                                repr(self.linear))

    def __eq__(self, other):
        if isinstance(other, FormattedSeq):
            if repr(self) == repr(other):
                return True
            else:
                return False
        return False

    def circularise(self):
        """FS.circularise() -> circularise FS"""
        self.linear = False
        return

    def linearise(self):
        """FS.linearise() -> linearise FS"""
        self.linear = True
        return

    def to_linear(self):
        """FS.to_linear() -> new linear FS instance"""
        new = self.__class__(self)
        new.linear = True
        return new

    def to_circular(self):
        """FS.to_circular() -> new circular FS instance"""
        new = self.__class__(self)
        new.linear = False
        return new

    def is_linear(self):
        """FS.is_linear() -> bool.

        True if the sequence will analysed as a linear sequence."""
        return self.linear

    def finditer(self, pattern, size):
        """FS.finditer(pattern, size) -> list.

        return a list of pattern into the sequence.
        the list is made of tuple (location, pattern.group).
        the latter is used with non palindromic sites.
        pattern is the regular expression pattern corresponding to the
        enzyme restriction site.
        size is the size of the restriction enzyme recognition-site size.
        """
        if self.is_linear():
            data = self.data
        else:
            data = self.data + self.data[1:size]
        return [(i.start(), i.group) for i in re.finditer(pattern, data)]

    def __getitem__(self, i):
        if self.lower:
            return self.klass((self.data[i]).lower(), self.alphabet)
        return self.klass(self.data[i], self.alphabet)


class RestrictionType(type):
    """RestrictionType. Type from which derives all enzyme classes.

    Implement the operator methods.
    """

    def __init__(cls, name='', bases=(), dct=None):
        """RE(name, bases, dct) -> RestrictionType instance.

        Not intended to be used in normal operation. The enzymes are
        instantiated when importing the module.

        see below."""
        if "-" in name:
            raise ValueError("Problem with hyphen in %s as enzyme name"
                             % repr(name))
        # 2011/11/26 - Nobody knows what this call was supposed to accomplish,
        # but all unit tests seem to pass without it.
        # super(RestrictionType, cls).__init__(cls, name, bases, dct)
        try:
            cls.compsite = re.compile(cls.compsite)
        except Exception as err:
            raise ValueError("Problem with regular expression, re.compiled(%s)"
                             % repr(cls.compsite))

    def __add__(cls, other):
        """RE.__add__(other) -> RestrictionBatch().

        if other is an enzyme returns a batch of the two enzymes.
        if other is already a RestrictionBatch add enzyme to it.
        """
        if isinstance(other, RestrictionType):
            return RestrictionBatch([cls, other])
        elif isinstance(other, RestrictionBatch):
            return other.add_nocheck(cls)
        else:
            raise TypeError

    def __div__(cls, other):
        """RE.__div__(other) -> list.

        RE/other
        returns RE.search(other)."""
        return cls.search(other)

    def __rdiv__(cls, other):
        """RE.__rdiv__(other) -> list.

        other/RE
        returns RE.search(other)."""
        return cls.search(other)

    def __truediv__(cls, other):
        """RE.__truediv__(other) -> list.

        RE/other
        returns RE.search(other)."""
        return cls.search(other)

    def __rtruediv__(cls, other):
        """RE.__rtruediv__(other) -> list.

        other/RE
        returns RE.search(other)."""
        return cls.search(other)

    def __floordiv__(cls, other):
        """RE.__floordiv__(other) -> list.

        RE//other
        returns RE.catalyse(other)."""
        return cls.catalyse(other)

    def __rfloordiv__(cls, other):
        """RE.__rfloordiv__(other) -> list.

        other//RE
        returns RE.catalyse(other)."""
        return cls.catalyse(other)

    def __str__(cls):
        """RE.__str__() -> str.

        return the name of the enzyme."""
        return cls.__name__

    def __repr__(cls):
        """RE.__repr__() -> str.

        used with eval or exec will instantiate the enzyme."""
        return "%s" % cls.__name__

    def __len__(cls):
        """RE.__len__() -> int.

        length of the recognition site."""
        return cls.size

    def __hash__(cls):
        # Python default is to use id(...)
        # This is consistent with the __eq__ implementation
        return id(cls)

    def __eq__(cls, other):
        """RE == other -> bool

        True if RE and other are the same enzyme.

        Specifically this checks they are the same Python object.
        """
        # assert (id(cls)==id(other)) == (other is cls) == (cls is other)
        return id(cls) == id(other)

    def __ne__(cls, other):
        """RE != other -> bool.
        isoschizomer strict, same recognition site, same restriction -> False
        all the other-> True

        WARNING - This is not the inverse of the __eq__ method.
        """
        if not isinstance(other, RestrictionType):
            return True
        elif cls.charac == other.charac:
            return False
        else:
            return True

    def __rshift__(cls, other):
        """RE >> other -> bool.

        neoschizomer : same recognition site, different restriction. -> True
        all the others :                                             -> False
        """
        if not isinstance(other, RestrictionType):
            return False
        elif cls.site == other.site and cls.charac != other.charac:
            return True
        else:
            return False

    def __mod__(cls, other):
        """a % b -> bool.

        Test compatibility of the overhang of a and b.
        True if a and b have compatible overhang.
        """
        if not isinstance(other, RestrictionType):
            raise TypeError(
                  'expected RestrictionType, got %s instead' % type(other))
        return cls._mod1(other)

    def __ge__(cls, other):
        """a >= b -> bool.

        a is greater or equal than b if the a site is longer than b site.
        if their site have the same length sort by alphabetical order of their
        names."""
        if not isinstance(other, RestrictionType):
            raise NotImplementedError
        if len(cls) > len(other):
            return True
        elif cls.size == len(other) and cls.__name__ >= other.__name__:
            return True
        else:
            return False

    def __gt__(cls, other):
        """a > b -> bool.

        sorting order:
                    1. size of the recognition site.
                    2. if equal size, alphabetical order of the names."""
        if not isinstance(other, RestrictionType):
            raise NotImplementedError
        if len(cls) > len(other):
            return True
        elif cls.size == len(other) and cls.__name__ > other.__name__:
            return True
        else:
            return False

    def __le__(cls, other):
        """a <= b -> bool.

        sorting order:
                    1. size of the recognition site.
                    2. if equal size, alphabetical order of the names.
        """
        if not isinstance(other, RestrictionType):
            raise NotImplementedError
        elif len(cls) < len(other):
            return True
        elif len(cls) == len(other) and cls.__name__ <= other.__name__:
            return True
        else:
            return False

    def __lt__(cls, other):
        """a < b -> bool.

        sorting order:
                    1. size of the recognition site.
                    2. if equal size, alphabetical order of the names.
        """
        if not isinstance(other, RestrictionType):
            raise NotImplementedError
        elif len(cls) < len(other):
            return True
        elif len(cls) == len(other) and cls.__name__ < other.__name__:
            return True
        else:
            return False


class AbstractCut(RestrictionType):
    """Implement the methods that are common to all restriction enzymes.

    All the methods are classmethod.

    For internal use only. Not meant to be instantiate.
    """

    @classmethod
    def search(cls, dna, linear=True):
        """RE.search(dna, linear=True) -> list.

        return a list of all the site of RE in dna. Compensate for circular
        sequences and so on.

        dna must be a Bio.Seq.Seq instance or a Bio.Seq.MutableSeq instance.

        if linear is False, the restriction sites than span over the boundaries
        will be included.

        The positions are the first base of the 3' fragment,
        i.e. the first base after the position the enzyme will cut.
        """
        #
        #   Separating search from _search allow a (very limited) optimisation
        #   of the search when using a batch of restriction enzymes.
        #   in this case the DNA is tested once by the class which implements
        #   the batch instead of being tested by each enzyme single.
        #   see RestrictionBatch.search() for example.
        #
        if isinstance(dna, FormattedSeq):
            cls.dna = dna
            return cls._search()
        else:
            cls.dna = FormattedSeq(dna, linear)
            return cls._search()

    @classmethod
    def all_suppliers(cls):
        """RE.all_suppliers -> print all the suppliers of R"""
        supply = sorted(x[0] for x in suppliers_dict.values())
        print(",\n".join(supply))
        return

    @classmethod
    def is_equischizomer(cls, other):
        """RE.is_equischizomers(other) -> bool.

        True if other is an isoschizomer of RE.
        False else.

        equischizomer <=> same site, same position of restriction.
        """
        return not cls != other

    @classmethod
    def is_neoschizomer(cls, other):
        """RE.is_neoschizomers(other) -> bool.

        True if other is an isoschizomer of RE.
        False else.

        neoschizomer <=> same site, different position of restriction.
        """
        return cls >> other

    @classmethod
    def is_isoschizomer(cls, other):
        """RE.is_isoschizomers(other) -> bool.

        True if other is an isoschizomer of RE.
        False else.

        isoschizomer <=> same site."""
        return (not cls != other) or cls >> other

    @classmethod
    def equischizomers(cls, batch=None):
        """RE.equischizomers([batch]) -> list.

        return a tuple of all the isoschizomers of RE.
        if batch is supplied it is used instead of the default AllEnzymes.

        equischizomer <=> same site, same position of restriction.
        """
        if not batch:
            batch = AllEnzymes
        r = [x for x in batch if not cls != x]
        i = r.index(cls)
        del r[i]
        r.sort()
        return r

    @classmethod
    def neoschizomers(cls, batch=None):
        """RE.neoschizomers([batch]) -> list.

        return a tuple of all the neoschizomers of RE.
        if batch is supplied it is used instead of the default AllEnzymes.

        neoschizomer <=> same site, different position of restriction."""
        if not batch:
            batch = AllEnzymes
        r = sorted(x for x in batch if cls >> x)
        return r

    @classmethod
    def isoschizomers(cls, batch=None):
        """RE.isoschizomers([batch]) -> list.

        return a tuple of all the equischizomers and neoschizomers of RE.
        if batch is supplied it is used instead of the default AllEnzymes.
        """
        if not batch:
            batch = AllEnzymes
        r = [x for x in batch if (cls >> x) or (not cls != x)]
        i = r.index(cls)
        del r[i]
        r.sort()
        return r

    @classmethod
    def frequency(cls):
        """RE.frequency() -> int.

        frequency of the site."""
        return cls.freq


class NoCut(AbstractCut):
    """Implement the methods specific to the enzymes that do not cut.

    These enzymes are generally enzymes that have been only partially
    characterised and the way they cut the DNA is unknow or enzymes for
    which the pattern of cut is to complex to be recorded in Rebase
    (ncuts values of 0 in emboss_e.###).

    When using search() with these enzymes the values returned are at the start
    of the restriction site.

    Their catalyse() method returns a TypeError.

    Unknown and NotDefined are also part of the base classes of these enzymes.

    Internal use only. Not meant to be instantiated.
    """

    @classmethod
    def cut_once(cls):
        """RE.cut_once() -> bool.

        True if the enzyme cut the sequence one time on each strand."""
        return False

    @classmethod
    def cut_twice(cls):
        """RE.cut_twice() -> bool.

        True if the enzyme cut the sequence twice on each strand."""
        return False

    @classmethod
    def _modify(cls, location):
        """RE._modify(location) -> int.

        for internal use only.

        location is an integer corresponding to the location of the match for
        the enzyme pattern in the sequence.
        _modify returns the real place where the enzyme will cut.

        example::

            EcoRI pattern : GAATTC
            EcoRI will cut after the G.
            so in the sequence:
                     ______
            GAATACACGGAATTCGA
                     |
                     10
            dna.finditer(GAATTC, 6) will return 10 as G is the 10th base
            EcoRI cut after the G so:
            EcoRI._modify(10) -> 11.

        if the enzyme cut twice _modify will returns two integer corresponding
        to each cutting site.
        """
        yield location

    @classmethod
    def _rev_modify(cls, location):
        """RE._rev_modify(location) -> generator of int.

        for internal use only.

        as _modify for site situated on the antiparallel strand when the
        enzyme is not palindromic
        """
        yield location

    @classmethod
    def characteristic(cls):
        """RE.characteristic() -> tuple.

        the tuple contains the attributes:
            fst5 -> first 5' cut ((current strand) or None
            fst3 -> first 3' cut (complementary strand) or None
            scd5 -> second 5' cut (current strand) or None
            scd5 -> second 3' cut (complementary strand) or None
            site -> recognition site.
        """
        return None, None, None, None, cls.site


class OneCut(AbstractCut):
    """Implement the methods specific to the enzymes that cut the DNA only once

    Correspond to ncuts values of 2 in emboss_e.###

    Internal use only. Not meant to be instantiated.
    """

    @classmethod
    def cut_once(cls):
        """RE.cut_once() -> bool.

        True if the enzyme cut the sequence one time on each strand.
        """
        return True

    @classmethod
    def cut_twice(cls):
        """RE.cut_twice() -> bool.

        True if the enzyme cut the sequence twice on each strand.
        """
        return False

    @classmethod
    def _modify(cls, location):
        """RE._modify(location) -> int.

        for internal use only.

        location is an integer corresponding to the location of the match for
        the enzyme pattern in the sequence.
        _modify returns the real place where the enzyme will cut.

        example::

            EcoRI pattern : GAATTC
            EcoRI will cut after the G.
            so in the sequence:
                     ______
            GAATACACGGAATTCGA
                     |
                     10
            dna.finditer(GAATTC, 6) will return 10 as G is the 10th base
            EcoRI cut after the G so:
            EcoRI._modify(10) -> 11.

        if the enzyme cut twice _modify will returns two integer corresponding
        to each cutting site.
        """
        yield location + cls.fst5

    @classmethod
    def _rev_modify(cls, location):
        """RE._rev_modify(location) -> generator of int.

        for internal use only.

        as _modify for site situated on the antiparallel strand when the
        enzyme is not palindromic
        """
        yield location - cls.fst3

    @classmethod
    def characteristic(cls):
        """RE.characteristic() -> tuple.

        the tuple contains the attributes:
            fst5 -> first 5' cut ((current strand) or None
            fst3 -> first 3' cut (complementary strand) or None
            scd5 -> second 5' cut (current strand) or None
            scd5 -> second 3' cut (complementary strand) or None
            site -> recognition site.
            """
        return cls.fst5, cls.fst3, None, None, cls.site


class TwoCuts(AbstractCut):
    """Implement the methods specific to the enzymes that cut the DNA twice

    Correspond to ncuts values of 4 in emboss_e.###

    Internal use only. Not meant to be instantiated."""

    @classmethod
    def cut_once(cls):
        """RE.cut_once() -> bool.

        True if the enzyme cut the sequence one time on each strand."""
        return False

    @classmethod
    def cut_twice(cls):
        """RE.cut_twice() -> bool.

        True if the enzyme cut the sequence twice on each strand.
        """
        return True

    @classmethod
    def _modify(cls, location):
        """RE._modify(location) -> int.

        for internal use only.

        location is an integer corresponding to the location of the match for
        the enzyme pattern in the sequence.
        _modify returns the real place where the enzyme will cut.

        example::

            EcoRI pattern : GAATTC
            EcoRI will cut after the G.
            so in the sequence:
                     ______
            GAATACACGGAATTCGA
                     |
                     10
            dna.finditer(GAATTC, 6) will return 10 as G is the 10th base
            EcoRI cut after the G so:
            EcoRI._modify(10) -> 11.

        if the enzyme cut twice _modify will returns two integer corresponding
        to each cutting site.
        """
        yield location + cls.fst5
        yield location + cls.scd5

    @classmethod
    def _rev_modify(cls, location):
        """RE._rev_modify(location) -> generator of int.

        for internal use only.

        as _modify for site situated on the antiparallel strand when the
        enzyme is not palindromic
        """
        yield location - cls.fst3
        yield location - cls.scd3

    @classmethod
    def characteristic(cls):
        """RE.characteristic() -> tuple.

        the tuple contains the attributes:
            fst5 -> first 5' cut ((current strand) or None
            fst3 -> first 3' cut (complementary strand) or None
            scd5 -> second 5' cut (current strand) or None
            scd5 -> second 3' cut (complementary strand) or None
            site -> recognition site.
        """
        return cls.fst5, cls.fst3, cls.scd5, cls.scd3, cls.site


class Meth_Dep(AbstractCut):
    """Implement the information about methylation.

    Enzymes of this class possess a site which is methylable.
    """

    @classmethod
    def is_methylable(cls):
        """RE.is_methylable() -> bool.

        True if the recognition site is a methylable.
        """
        return True


class Meth_Undep(AbstractCut):
    """Implement information about methylation sensitibility.

    Enzymes of this class are not sensible to methylation.
    """

    @classmethod
    def is_methylable(cls):
        """RE.is_methylable() -> bool.

        True if the recognition site is a methylable.
        """
        return False


class Palindromic(AbstractCut):
    """Implement the methods specific to the enzymes which are palindromic

    palindromic means : the recognition site and its reverse complement are
                        identical.
    Remarks     : an enzyme with a site CGNNCG is palindromic even if some
                  of the sites that it will recognise are not.
                  for example here : CGAACG

    Internal use only. Not meant to be instantiated."""

    @classmethod
    def _search(cls):
        """RE._search() -> list.

        for internal use only.

        implement the search method for palindromic and non palindromic enzyme.
        """
        siteloc = cls.dna.finditer(cls.compsite, cls.size)
        cls.results = [r for s, g in siteloc for r in cls._modify(s)]
        if cls.results:
            cls._drop()
        return cls.results

    @classmethod
    def is_palindromic(cls):
        """RE.is_palindromic() -> bool.

        True if the recognition site is a palindrom.
        """
        return True


class NonPalindromic(AbstractCut):
    """Implement the methods specific to the enzymes which are not palindromic

    palindromic means : the recognition site and its reverse complement are
                        identical.

    Internal use only. Not meant to be instantiated."""

    @classmethod
    def _search(cls):
        """RE._search() -> list.

        for internal use only.

        implement the search method for palindromic and non palindromic enzyme.
        """
        iterator = cls.dna.finditer(cls.compsite, cls.size)
        cls.results = []
        modif = cls._modify
        revmodif = cls._rev_modify
        s = str(cls)
        cls.on_minus = []
        for start, group in iterator:
            if group(s):
                cls.results += [r for r in modif(start)]
            else:
                cls.on_minus += [r for r in revmodif(start)]
        cls.results += cls.on_minus
        if cls.results:
            cls.results.sort()
            cls._drop()
        return cls.results

    @classmethod
    def is_palindromic(cls):
        """RE.is_palindromic() -> bool.

        True if the recognition site is a palindrom.
        """
        return False


class Unknown(AbstractCut):
    """Implement the methods specific to the enzymes for which the overhang
    is unknown.

    These enzymes are also NotDefined and NoCut.

    Internal use only. Not meant to be instantiated.
    """

    @classmethod
    def catalyse(cls, dna, linear=True):
        """RE.catalyse(dna, linear=True) -> tuple of DNA.
        RE.catalyze(dna, linear=True) -> tuple of DNA.

        return a tuple of dna as will be produced by using RE to restrict the
        dna.

        dna must be a Bio.Seq.Seq instance or a Bio.Seq.MutableSeq instance.

        if linear is False, the sequence is considered to be circular and the
        output will be modified accordingly.
        """
        raise NotImplementedError('%s restriction is unknown.'
                                  % cls.__name__)
    catalyze = catalyse

    @classmethod
    def is_blunt(cls):
        """RE.is_blunt() -> bool.

        True if the enzyme produces blunt end.

        see also:
            RE.is_3overhang()
            RE.is_5overhang()
            RE.is_unknown()
        """
        return False

    @classmethod
    def is_5overhang(cls):
        """RE.is_5overhang() -> bool.

        True if the enzyme produces 5' overhang sticky end.

        see also:
            RE.is_3overhang()
            RE.is_blunt()
            RE.is_unknown()
        """
        return False

    @classmethod
    def is_3overhang(cls):
        """RE.is_3overhang() -> bool.

        True if the enzyme produces 3' overhang sticky end.

        see also:
            RE.is_5overhang()
            RE.is_blunt()
            RE.is_unknown()
        """
        return False

    @classmethod
    def overhang(cls):
        """RE.overhang() -> str. type of overhang of the enzyme.,

        can be "3' overhang", "5' overhang", "blunt", "unknown"
        """
        return 'unknown'

    @classmethod
    def compatible_end(cls):
        """RE.compatible_end() -> list.

        list of all the enzymes that share compatible end with RE.
        """
        return []

    @classmethod
    def _mod1(cls, other):
        """RE._mod1(other) -> bool.

        for internal use only

        test for the compatibility of restriction ending of RE and other.
        """
        return False


class Blunt(AbstractCut):
    """Implement the methods specific to the enzymes for which the overhang
    is blunt.

    The enzyme cuts the + strand and the - strand of the DNA at the same
    place.

    Internal use only. Not meant to be instantiated.
    """

    @classmethod
    def catalyse(cls, dna, linear=True):
        """RE.catalyse(dna, linear=True) -> tuple of DNA.
        RE.catalyze(dna, linear=True) -> tuple of DNA.

        return a tuple of dna as will be produced by using RE to restrict the
        dna.

        dna must be a Bio.Seq.Seq instance or a Bio.Seq.MutableSeq instance.

        if linear is False, the sequence is considered to be circular and the
        output will be modified accordingly.
        """
        r = cls.search(dna, linear)
        d = cls.dna
        if not r:
            return d[1:],
        fragments = []
        length = len(r) - 1
        if d.is_linear():
            #
            #   START of the sequence to FIRST site.
            #
            fragments.append(d[1:r[0]])
            if length:
                #
                #   if more than one site add them.
                #
                fragments += [d[r[x]:r[x + 1]] for x in range(length)]
            #
            #   LAST site to END of the sequence.
            #
            fragments.append(d[r[-1]:])
        else:
            #
            #   circular : bridge LAST site to FIRST site.
            #
            fragments.append(d[r[-1]:] + d[1:r[0]])
            if not length:
                #
                #   one site we finish here.
                #
                return tuple(fragments)
            #
            #   add the others.
            #
            fragments += [d[r[x]:r[x + 1]] for x in range(length)]
        return tuple(fragments)
    catalyze = catalyse

    @classmethod
    def is_blunt(cls):
        """RE.is_blunt() -> bool.

        True if the enzyme produces blunt end.

        see also:
            RE.is_3overhang()
            RE.is_5overhang()
            RE.is_unknown()
        """
        return True

    @classmethod
    def is_5overhang(cls):
        """RE.is_5overhang() -> bool.

        True if the enzyme produces 5' overhang sticky end.

        see also:
            RE.is_3overhang()
            RE.is_blunt()
            RE.is_unknown()
        """
        return False

    @classmethod
    def is_3overhang(cls):
        """RE.is_3overhang() -> bool.

        True if the enzyme produces 3' overhang sticky end.

        see also:
            RE.is_5overhang()
            RE.is_blunt()
            RE.is_unknown()
        """
        return False

    @classmethod
    def overhang(cls):
        """RE.overhang() -> str. type of overhang of the enzyme.,

        can be "3' overhang", "5' overhang", "blunt", "unknown"
        """
        return 'blunt'

    @classmethod
    def compatible_end(cls, batch=None):
        """RE.compatible_end() -> list.

        list of all the enzymes that share compatible end with RE.
        """
        if not batch:
            batch = AllEnzymes
        r = sorted(x for x in iter(AllEnzymes) if x.is_blunt())
        return r

    @staticmethod
    def _mod1(other):
        """RE._mod1(other) -> bool.

        for internal use only

        test for the compatibility of restriction ending of RE and other.
        """
        return issubclass(other, Blunt)


class Ov5(AbstractCut):
    """Implement the methods specific to the enzymes for which the overhang
    is recessed in 3'.

    The enzyme cuts the + strand after the - strand of the DNA.

    Internal use only. Not meant to be instantiated.
    """

    @classmethod
    def catalyse(cls, dna, linear=True):
        """RE.catalyse(dna, linear=True) -> tuple of DNA.
        RE.catalyze(dna, linear=True) -> tuple of DNA.

        return a tuple of dna as will be produced by using RE to restrict the
        dna.

        dna must be a Bio.Seq.Seq instance or a Bio.Seq.MutableSeq instance.

        if linear is False, the sequence is considered to be circular and the
        output will be modified accordingly.
        """
        r = cls.search(dna, linear)
        d = cls.dna
        if not r:
            return d[1:],
        length = len(r) - 1
        fragments = []
        if d.is_linear():
            #
            #   START of the sequence to FIRST site.
            #
            fragments.append(d[1:r[0]])
            if length:
                #
                #   if more than one site add them.
                #
                fragments += [d[r[x]:r[x + 1]] for x in range(length)]
            #
            #   LAST site to END of the sequence.
            #
            fragments.append(d[r[-1]:])
        else:
            #
            #   circular : bridge LAST site to FIRST site.
            #
            fragments.append(d[r[-1]:] + d[1:r[0]])
            if not length:
                #
                #   one site we finish here.
                #
                return tuple(fragments)
            #
            #   add the others.
            #
            fragments += [d[r[x]:r[x + 1]] for x in range(length)]
        return tuple(fragments)
    catalyze = catalyse

    @classmethod
    def is_blunt(cls):
        """RE.is_blunt() -> bool.

        True if the enzyme produces blunt end.

        see also:
            RE.is_3overhang()
            RE.is_5overhang()
            RE.is_unknown()
        """
        return False

    @classmethod
    def is_5overhang(cls):
        """RE.is_5overhang() -> bool.

        True if the enzyme produces 5' overhang sticky end.

        see also:
            RE.is_3overhang()
            RE.is_blunt()
            RE.is_unknown()
        """
        return True

    @classmethod
    def is_3overhang(cls):
        """RE.is_3overhang() -> bool.

        True if the enzyme produces 3' overhang sticky end.

        see also:
            RE.is_5overhang()
            RE.is_blunt()
            RE.is_unknown()
        """
        return False

    @classmethod
    def overhang(cls):
        """RE.overhang() -> str. type of overhang of the enzyme.,

        can be "3' overhang", "5' overhang", "blunt", "unknown"
        """
        return "5' overhang"

    @classmethod
    def compatible_end(cls, batch=None):
        """RE.compatible_end() -> list.

        list of all the enzymes that share compatible end with RE."""
        if not batch:
            batch = AllEnzymes
        r = sorted(x for x in iter(AllEnzymes) if x.is_5overhang() and
                   x % cls)
        return r

    @classmethod
    def _mod1(cls, other):
        """RE._mod1(other) -> bool.

        for internal use only

        test for the compatibility of restriction ending of RE and other.
        """
        if issubclass(other, Ov5):
            return cls._mod2(other)
        else:
            return False


class Ov3(AbstractCut):
    """Implement the methods specific to the enzymes for which the overhang
    is recessed in 5'.

    The enzyme cuts the - strand after the + strand of the DNA.

    Internal use only. Not meant to be instantiated.
    """

    @classmethod
    def catalyse(cls, dna, linear=True):
        """RE.catalyse(dna, linear=True) -> tuple of DNA.
        RE.catalyze(dna, linear=True) -> tuple of DNA.

        return a tuple of dna as will be produced by using RE to restrict the
        dna.

        dna must be a Bio.Seq.Seq instance or a Bio.Seq.MutableSeq instance.

        if linear is False, the sequence is considered to be circular and the
        output will be modified accordingly.
        """
        r = cls.search(dna, linear)
        d = cls.dna
        if not r:
            return d[1:],
        fragments = []
        length = len(r) - 1
        if d.is_linear():
            #
            #   START of the sequence to FIRST site.
            #
            fragments.append(d[1:r[0]])
            if length:
                #
                #   if more than one site add them.
                #
                fragments += [d[r[x]:r[x + 1]] for x in range(length)]
            #
            #   LAST site to END of the sequence.
            #
            fragments.append(d[r[-1]:])
        else:
            #
            #   circular : bridge LAST site to FIRST site.
            #
            fragments.append(d[r[-1]:] + d[1:r[0]])
            if not length:
                #
                #   one site we finish here.
                #
                return tuple(fragments)
            #
            #   add the others.
            #
            fragments += [d[r[x]:r[x + 1]] for x in range(length)]
        return tuple(fragments)
    catalyze = catalyse

    @classmethod
    def is_blunt(cls):
        """RE.is_blunt() -> bool.

        True if the enzyme produces blunt end.

        see also:
            RE.is_3overhang()
            RE.is_5overhang()
            RE.is_unknown()
        """
        return False

    @classmethod
    def is_5overhang(cls):
        """RE.is_5overhang() -> bool.

        True if the enzyme produces 5' overhang sticky end.

        see also:
            RE.is_3overhang()
            RE.is_blunt()
            RE.is_unknown()
        """
        return False

    @classmethod
    def is_3overhang(cls):
        """RE.is_3overhang() -> bool.

        True if the enzyme produces 3' overhang sticky end.

        see also:
            RE.is_5overhang()
            RE.is_blunt()
            RE.is_unknown()
        """
        return True

    @classmethod
    def overhang(cls):
        """RE.overhang() -> str. type of overhang of the enzyme.,

        can be "3' overhang", "5' overhang", "blunt", "unknown"
        """
        return "3' overhang"

    @classmethod
    def compatible_end(cls, batch=None):
        """RE.compatible_end() -> list.

        list of all the enzymes that share compatible end with RE.
        """
        if not batch:
            batch = AllEnzymes
        r = sorted(x for x in iter(AllEnzymes) if x.is_3overhang() and
                   x % cls)
        return r

    @classmethod
    def _mod1(cls, other):
        """RE._mod1(other) -> bool.

        for internal use only

        test for the compatibility of restriction ending of RE and other.
        """
        #
        #   called by RE._mod1(other) when the one of the enzyme is ambiguous
        #
        if issubclass(other, Ov3):
            return cls._mod2(other)
        else:
            return False


class Defined(AbstractCut):
    """Implement the methods specific to the enzymes for which the overhang
    and the cut are not variable.

    Typical example : EcoRI -> G^AATT_C
                      The overhang will always be AATT
    Notes:
        Blunt enzymes are always defined. even if there site is GGATCCNNN^_N
        There overhang is always the same : blunt!

    Internal use only. Not meant to be instantiated."""

    @classmethod
    def _drop(cls):
        """RE._drop() -> list.

        for internal use only.

        drop the site that are situated outside the sequence in linear
        sequence. modify the index for site in circular sequences.
        """
        #
        #   remove or modify the results that are outside the sequence.
        #   This is necessary since after finding the site we add the distance
        #   from the site to the cut with the _modify and _rev_modify methods.
        #   For linear we will remove these sites altogether.
        #   For circular sequence, we modify the result rather than _drop it
        #   since the site is in the sequence.
        #
        length = len(cls.dna)
        drop = itertools.dropwhile
        take = itertools.takewhile
        if cls.dna.is_linear():
            cls.results = [x for x in drop(lambda x:x < 1, cls.results)]
            cls.results = [x for x in take(lambda x:x < length, cls.results)]
        else:
            for index, location in enumerate(cls.results):
                if location < 1:
                    cls.results[index] += length
                else:
                    break
            for index, location in enumerate(cls.results[::-1]):
                if location > length:
                    cls.results[-(index + 1)] -= length
                else:
                    break
        return

    @classmethod
    def is_defined(cls):
        """RE.is_defined() -> bool.

        True if the sequence recognised and cut is constant,
        i.e. the recognition site is not degenerated AND the enzyme cut inside
        the site.

        see also:
            RE.is_ambiguous()
            RE.is_unknown()
        """
        return True

    @classmethod
    def is_ambiguous(cls):
        """RE.is_ambiguous() -> bool.

        True if the sequence recognised and cut is ambiguous,
        i.e. the recognition site is degenerated AND/OR the enzyme cut outside
        the site.

        see also:
            RE.is_defined()
            RE.is_unknown()
        """
        return False

    @classmethod
    def is_unknown(cls):
        """RE.is_unknown() -> bool.

        True if the sequence is unknown,
        i.e. the recognition site has not been characterised yet.

        see also:
            RE.is_defined()
            RE.is_ambiguous()
        """
        return False

    @classmethod
    def elucidate(cls):
        """RE.elucidate() -> str

        return a representation of the site with the cut on the (+) strand
        represented as '^' and the cut on the (-) strand as '_'.
        ie:
        >>> EcoRI.elucidate()   # 5' overhang
        'G^AATT_C'
        >>> KpnI.elucidate()    # 3' overhang
        'G_GTAC^C'
        >>> EcoRV.elucidate()   # blunt
        'GAT^_ATC'
        >>> SnaI.elucidate()    # NotDefined, cut profile unknown.
        '? GTATAC ?'
        >>>
        """
        f5 = cls.fst5
        f3 = cls.fst3
        site = cls.site
        if cls.cut_twice():
            re = 'cut twice, not yet implemented sorry.'
        elif cls.is_5overhang():
            if f5 == f3 == 0:
                re = 'N^' + cls.site + '_N'
            elif f3 == 0:
                re = site[:f5] + '^' + site[f5:] + '_N'
            else:
                re = site[:f5] + '^' + site[f5:f3] + '_' + site[f3:]
        elif cls.is_blunt():
            re = site[:f5] + '^_' + site[f5:]
        else:
            if f5 == f3 == 0:
                re = 'N_' + site + '^N'
            else:
                re = site[:f3] + '_' + site[f3:f5] + '^' + site[f5:]
        return re

    @classmethod
    def _mod2(cls, other):
        """RE._mod2(other) -> bool.

        for internal use only

        test for the compatibility of restriction ending of RE and other.
        """
        #
        #   called by RE._mod1(other) when the one of the enzyme is ambiguous
        #
        if other.ovhgseq == cls.ovhgseq:
            return True
        elif issubclass(other, Ambiguous):
            return other._mod2(cls)
        else:
            return False


class Ambiguous(AbstractCut):
    """Implement the methods specific to the enzymes for which the overhang
    is variable.

    Typical example : BstXI -> CCAN_NNNN^NTGG
                      The overhang can be any sequence of 4 bases.
    Notes:
        Blunt enzymes are always defined. even if there site is GGATCCNNN^_N
        There overhang is always the same : blunt!

    Internal use only. Not meant to be instantiated.
    """

    @classmethod
    def _drop(cls):
        """RE._drop() -> list.

        for internal use only.

        drop the site that are situated outside the sequence in linear
        sequence. modify the index for site in circular sequences.
        """
        length = len(cls.dna)
        drop = itertools.dropwhile
        take = itertools.takewhile
        if cls.dna.is_linear():
            cls.results = [x for x in drop(lambda x: x < 1, cls.results)]
            cls.results = [x for x in take(lambda x: x <
                                            length, cls.results)]
        else:
            for index, location in enumerate(cls.results):
                if location < 1:
                    cls.results[index] += length
                else:
                    break
            for index, location in enumerate(cls.results[::-1]):
                if location > length:
                    cls.results[-(index + 1)] -= length
                else:
                    break
        return

    @classmethod
    def is_defined(cls):
        """RE.is_defined() -> bool.

        True if the sequence recognised and cut is constant,
        i.e. the recognition site is not degenerated AND the enzyme cut inside
        the site.

        see also:
            RE.is_ambiguous()
            RE.is_unknown()
        """
        return False

    @classmethod
    def is_ambiguous(cls):
        """RE.is_ambiguous() -> bool.

        True if the sequence recognised and cut is ambiguous,
        i.e. the recognition site is degenerated AND/OR the enzyme cut outside
        the site.

        see also:
            RE.is_defined()
            RE.is_unknown()
        """
        return True

    @classmethod
    def is_unknown(cls):
        """RE.is_unknown() -> bool.

        True if the sequence is unknown,
        i.e. the recognition site has not been characterised yet.

        see also:
            RE.is_defined()
            RE.is_ambiguous()
        """
        return False

    @classmethod
    def _mod2(cls, other):
        """RE._mod2(other) -> bool.

        for internal use only

        test for the compatibility of restriction ending of RE and other.
        """
        #
        #   called by RE._mod1(other) when the one of the enzyme is ambiguous
        #
        if len(cls.ovhgseq) != len(other.ovhgseq):
            return False
        else:
            se = cls.ovhgseq
            for base in se:
                if base in 'ATCG':
                    pass
                if base in 'N':
                    se = '.'.join(se.split('N'))
                if base in 'RYWMSKHDBV':
                    expand = '[' + matching[base] + ']'
                    se = expand.join(se.split(base))
            if re.match(se, other.ovhgseq):
                return True
            else:
                return False

    @classmethod
    def elucidate(cls):
        """RE.elucidate() -> str

        return a representation of the site with the cut on the (+) strand
        represented as '^' and the cut on the (-) strand as '_'.
        ie:
        >>> EcoRI.elucidate()   # 5' overhang
        'G^AATT_C'
        >>> KpnI.elucidate()    # 3' overhang
        'G_GTAC^C'
        >>> EcoRV.elucidate()   # blunt
        'GAT^_ATC'
        >>> SnaI.elucidate()     # NotDefined, cut profile unknown.
        '? GTATAC ?'
        >>>
        """
        f5 = cls.fst5
        f3 = cls.fst3
        length = len(cls)
        site = cls.site
        if cls.cut_twice():
            re = 'cut twice, not yet implemented sorry.'
        elif cls.is_5overhang():
            if f3 == f5 == 0:
                re = 'N^' + site + '_N'
            elif 0 <= f5 <= length and 0 <= f3 + length <= length:
                re = site[:f5] + '^' + site[f5:f3] + '_' + site[f3:]
            elif 0 <= f5 <= length:
                re = site[:f5] + '^' + site[f5:] + f3 * 'N' + '_N'
            elif 0 <= f3 + length <= length:
                re = 'N^' + abs(f5) * 'N' + site[:f3] + '_' + site[f3:]
            elif f3 + length < 0:
                re = 'N^' * abs(f5) * 'N' + '_' + abs(length + f3) * 'N' + site
            elif f5 > length:
                re = site + (f5 - length) * 'N' + '^' + (length +
                                                         f3 - f5) * 'N' + '_N'
            else:
                re = 'N^' + abs(f5) * 'N' + site + f3 * 'N' + '_N'
        elif cls.is_blunt():
            if f5 < 0:
                re = 'N^_' + abs(f5) * 'N' + site
            elif f5 > length:
                re = site + (f5 - length) * 'N' + '^_N'
            else:
                raise ValueError('%s.easyrepr() : error f5=%i'
                                 % (cls.name, f5))
        else:
            if f3 == 0:
                if f5 == 0:
                    re = 'N_' + site + '^N'
                else:
                    re = site + '_' + (f5 - length) * 'N' + '^N'
            elif 0 < f3 + length <= length and 0 <= f5 <= length:
                re = site[:f3] + '_' + site[f3:f5] + '^' + site[f5:]
            elif 0 < f3 + length <= length:
                re = site[:f3] + '_' + site[f3:] + (f5 - length) * 'N' + '^N'
            elif 0 <= f5 <= length:
                re = 'N_' + 'N' * (f3 + length) + site[:f5] + '^' + site[f5:]
            elif f3 > 0:
                re = site + f3 * 'N' + '_' + (f5 - f3 - length) * 'N' + '^N'
            elif f5 < 0:
                re = 'N_' + abs(f3 - f5 + length) * 'N' + '^' + abs(f5) * 'N' \
                     + site
            else:
                re = 'N_' + abs(f3 + length) * 'N' + site + (f5 - length) * \
                     'N' + '^N'
        return re


class NotDefined(AbstractCut):
    """Implement the methods specific to the enzymes for which the overhang
    is not characterised.

    Correspond to NoCut and Unknown.

    Internal use only. Not meant to be instantiated.
    """

    @classmethod
    def _drop(cls):
        """RE._drop() -> list.

        for internal use only.

        drop the site that are situated outside the sequence in linear
        sequence. modify the index for site in circular sequences.
        """
        if cls.dna.is_linear():
            return
        else:
            length = len(cls.dna)
            for index, location in enumerate(cls.results):
                if location < 1:
                    cls.results[index] += length
                else:
                    break
            for index, location in enumerate(cls.results[:-1]):
                if location > length:
                    cls.results[-(index + 1)] -= length
                else:
                    break
        return

    @classmethod
    def is_defined(cls):
        """RE.is_defined() -> bool.

        True if the sequence recognised and cut is constant,
        i.e. the recognition site is not degenerated AND the enzyme cut inside
        the site.

        see also:
            RE.is_ambiguous()
            RE.is_unknown()
        """
        return False

    @classmethod
    def is_ambiguous(cls):
        """RE.is_ambiguous() -> bool.

        True if the sequence recognised and cut is ambiguous,
        i.e. the recognition site is degenerated AND/OR the enzyme cut outside
        the site.

        see also:
            RE.is_defined()
            RE.is_unknown()
        """
        return False

    @classmethod
    def is_unknown(cls):
        """RE.is_unknown() -> bool.

        True if the sequence is unknown,
        i.e. the recognition site has not been characterised yet.

        see also:
            RE.is_defined()
            RE.is_ambiguous()"""
        return True

    @classmethod
    def _mod2(cls, other):
        """RE._mod2(other) -> bool.

        for internal use only

        test for the compatibility of restriction ending of RE and other.
        """
        #
        #   Normally we should not arrive here. But well better safe than
        #   sorry.
        #   the overhang is not defined we are compatible with nobody.
        #   could raise an Error may be rather than return quietly.
        #
        # return False
        raise ValueError("%s.mod2(%s), %s : NotDefined. pas glop pas glop!"
                         % (str(cls), str(other), str(cls)))

    @classmethod
    def elucidate(cls):
        """RE.elucidate() -> str

        return a representation of the site with the cut on the (+) strand
        represented as '^' and the cut on the (-) strand as '_'.
        ie:
        >>> EcoRI.elucidate()   # 5' overhang
        'G^AATT_C'
        >>> KpnI.elucidate()    # 3' overhang
        'G_GTAC^C'
        >>> EcoRV.elucidate()   # blunt
        'GAT^_ATC'
        >>> SnaI.elucidate()     # NotDefined, cut profile unknown.
        '? GTATAC ?'
        >>>
        """
        return '? %s ?' % cls.site


class Commercially_available(AbstractCut):
    #
    #   Recent addition to Rebase make this naming convention uncertain.
    #   May be better to says enzymes which have a supplier.
    #
    """Implement the methods specific to the enzymes which are commercially
    available.

    Internal use only. Not meant to be instantiated.
    """

    @classmethod
    def suppliers(cls):
        """RE.suppliers() -> print the suppliers of RE."""
        for s in cls.suppl:
            print(suppliers_dict[s][0] + ',')
        return

    @classmethod
    def supplier_list(cls):
        """RE.supplier_list() -> list.

        list of the supplier names for RE.
        """
        return [v[0] for k, v in suppliers_dict.items() if k in cls.suppl]

    @classmethod
    def buffers(cls, supplier):
        """RE.buffers(supplier) -> string.

        not implemented yet.
        """
        return

    @classmethod
    def is_comm(cls):
        """RE.iscomm() -> bool.

        True if RE has suppliers.
        """
        return True


class Not_available(AbstractCut):
    """Implement the methods specific to the enzymes which are not commercially
    available.

    Internal use only. Not meant to be instantiated.
    """

    @staticmethod
    def suppliers():
        """RE.suppliers() -> print the suppliers of RE."""
        return None

    @classmethod
    def supplier_list(cls):
        """RE.supplier_list() -> list.

        list of the supplier names for RE.
        """
        return []

    @classmethod
    def buffers(cls, supplier):
        """RE.buffers(supplier) -> string.

        not implemented yet.
        """
        raise TypeError("Enzyme not commercially available.")

    @classmethod
    def is_comm(cls):
        """RE.iscomm() -> bool.

        True if RE has suppliers.
        """
        return False


###############################################################################
#                                                                             #
#                       Restriction Batch                                     #
#                                                                             #
###############################################################################


class RestrictionBatch(set):

    def __init__(self, first=(), suppliers=()):
        """RestrictionBatch([sequence]) -> new RestrictionBatch."""
        first = [self.format(x) for x in first]
        first += [eval(x) for n in suppliers for x in suppliers_dict[n][1]]
        set.__init__(self, first)
        self.mapping = dict.fromkeys(self)
        self.already_mapped = None

    def __str__(self):
        if len(self) < 5:
            return '+'.join(self.elements())
        else:
            return '...'.join(('+'.join(self.elements()[:2]),
                               '+'.join(self.elements()[-2:])))

    def __repr__(self):
        return 'RestrictionBatch(%s)' % self.elements()

    def __contains__(self, other):
        try:
            other = self.format(other)
        except ValueError:  # other is not a restriction enzyme
            return False
        return set.__contains__(self, other)

    def __div__(self, other):
        return self.search(other)

    def __rdiv__(self, other):
        return self.search(other)

    def get(self, enzyme, add=False):
        """B.get(enzyme[, add]) -> enzyme class.

        if add is True and enzyme is not in B add enzyme to B.
        if add is False (which is the default) only return enzyme.
        if enzyme is not a RestrictionType or can not be evaluated to
        a RestrictionType, raise a ValueError.
        """
        e = self.format(enzyme)
        if e in self:
            return e
        elif add:
            self.add(e)
            return e
        else:
            raise ValueError('enzyme %s is not in RestrictionBatch'
                             % e.__name__)

    def lambdasplit(self, func):
        """B.lambdasplit(func) -> RestrictionBatch .

        the new batch will contains only the enzymes for which
        func return True.
        """
        d = [x for x in filter(func, self)]
        new = RestrictionBatch()
        new._data = dict(zip(d, [True] * len(d)))
        return new

    def add_supplier(self, letter):
        """B.add_supplier(letter) -> add a new set of enzyme to B.

        letter represents the suppliers as defined in the dictionary
        RestrictionDictionary.suppliers
        return None.
        raise a KeyError if letter is not a supplier code.
        """
        supplier = suppliers_dict[letter]
        self.suppliers.append(letter)
        for x in supplier[1]:
            self.add_nocheck(eval(x))
        return

    def current_suppliers(self):
        """B.current_suppliers() -> add a new set of enzyme to B.

        return a sorted list of the suppliers which have been used to
        create the batch.
        """
        suppl_list = sorted(suppliers_dict[x][0] for x in self.suppliers)
        return suppl_list

    def __iadd__(self, other):
        """ b += other -> add other to b, check the type of other."""
        self.add(other)
        return self

    def __add__(self, other):
        """ b + other -> new RestrictionBatch."""
        new = self.__class__(self)
        new.add(other)
        return new

    def remove(self, other):
        """B.remove(other) -> remove other from B if other is a
        RestrictionType.

        Safe set.remove method. Verify that other is a RestrictionType or can
        be evaluated to a RestrictionType.
        raise a ValueError if other can not be evaluated to a RestrictionType.
        raise a KeyError if other is not in B.
        """
        return set.remove(self, self.format(other))

    def add(self, other):
        """B.add(other) -> add other to B if other is a RestrictionType.

        Safe set.add method. Verify that other is a RestrictionType or can be
        evaluated to a RestrictionType.
        raise a ValueError if other can not be evaluated to a RestrictionType.
        """
        return set.add(self, self.format(other))

    def add_nocheck(self, other):
        """B.add_nocheck(other) -> add other to B. don't check type of other.
        """
        return set.add(self, other)

    def format(self, y):
        """B.format(y) -> RestrictionType or raise ValueError.

        if y is a RestrictionType return y
        if y can be evaluated to a RestrictionType return eval(y)
        raise a Value Error in all other case.
        """
        try:
            if isinstance(y, RestrictionType):
                return y
            elif isinstance(eval(str(y)), RestrictionType):
                return eval(y)
            else:
                pass
        except (NameError, SyntaxError):
            pass
        raise ValueError('%s is not a RestrictionType' % y.__class__)

    def is_restriction(self, y):
        """B.is_restriction(y) -> bool.

        True is y or eval(y) is a RestrictionType.
        """
        return (isinstance(y, RestrictionType) or
                isinstance(eval(str(y)), RestrictionType))

    def split(self, *classes, **bool):
        """B.split(class, [class.__name__ = True]) -> new RestrictionBatch.

        it works but it is slow, so it has really an interest when splitting
        over multiple conditions.
        """
        def splittest(element):
            for klass in classes:
                b = bool.get(klass.__name__, True)
                if issubclass(element, klass):
                    if b:
                        continue
                    else:
                        return False
                elif b:
                    return False
                else:
                    continue
            return True
        d = [k for k in filter(splittest, self)]
        new = RestrictionBatch()
        new._data = dict(zip(d, [True] * len(d)))
        return new

    def elements(self):
        """B.elements() -> tuple.

        give all the names of the enzymes in B sorted alphabetically.
        """
        l = sorted(str(e) for e in self)
        return l

    def as_string(self):
        """B.as_string() -> list.

        return a list of the name of the elements of B.
        """
        return [str(e) for e in self]

    @classmethod
    def suppl_codes(cls):
        """B.suppl_codes() -> dict

        letter code for the suppliers
        """
        supply = dict((k, v[0]) for k, v in suppliers_dict.items())
        return supply

    @classmethod
    def show_codes(cls):
        """B.show_codes() -> letter codes for the suppliers"""
        supply = [' = '.join(i) for i in cls.suppl_codes().items()]
        print('\n'.join(supply))
        return

    def search(self, dna, linear=True):
        """B.search(dna) -> dict."""
        #
        #   here we replace the search method of the individual enzymes
        #   with one unique testing method.
        #
        if not hasattr(self, "already_mapped"):
            # TODO - Why does this happen!
            # Try the "doctest" at the start of PrintFormat.py
            self.already_mapped = None
        if isinstance(dna, DNA):
            # For the searching, we just care about the sequence as a string,
            # if that is the same we can use the cached search results.
            # At the time of writing, Seq == method isn't implemented,
            # and therefore does object identity which is stricter.
            if (str(dna), linear) == self.already_mapped:
                return self.mapping
            else:
                self.already_mapped = str(dna), linear
                fseq = FormattedSeq(dna, linear)
                self.mapping = dict((x, x.search(fseq)) for x in self)
                return self.mapping
        elif isinstance(dna, FormattedSeq):
            if (str(dna), dna.linear) == self.already_mapped:
                return self.mapping
            else:
                self.already_mapped = str(dna), dna.linear
                self.mapping = dict((x, x.search(dna)) for x in self)
                return self.mapping
        raise TypeError("Expected Seq or MutableSeq instance, got %s instead"
                        % type(dna))

###############################################################################
#                                                                             #
#                       Restriction Analysis                                  #
#                                                                             #
###############################################################################


class Analysis(RestrictionBatch, PrintFormat):

    def __init__(self, restrictionbatch=RestrictionBatch(), sequence=DNA(''),
                 linear=True):
        """Analysis([restrictionbatch [, sequence] linear=True]) -> New Analysis class.

        For most of the method of this class if a dictionary is given it will
        be used as the base to calculate the results.
        If no dictionary is given a new analysis using the Restriction Batch
        which has been given when the Analysis class has been instantiated."""
        RestrictionBatch.__init__(self, restrictionbatch)
        self.rb = restrictionbatch
        self.sequence = sequence
        self.linear = linear
        if self.sequence:
            self.search(self.sequence, self.linear)

    def __repr__(self):
        return 'Analysis(%s,%s,%s)' %\
               (repr(self.rb), repr(self.sequence), self.linear)

    def _sub_set(self, wanted):
        """A._sub_set(other_set) -> dict.

        Internal use only.

        screen the results through wanted set.
        Keep only the results for which the enzymes is in wanted set.
        """
        return dict((k, v) for k, v in self.mapping.items() if k in wanted)

    def _boundaries(self, start, end):
        """A._boundaries(start, end) -> tuple.

        Format the boundaries for use with the methods that limit the
        search to only part of the sequence given to analyse.
        """
        if not isinstance(start, int):
            raise TypeError('expected int, got %s instead' % type(start))
        if not isinstance(end, int):
            raise TypeError('expected int, got %s instead' % type(end))
        if start < 1:
            start += len(self.sequence)
        if end < 1:
            end += len(self.sequence)
        if start < end:
            pass
        else:
            start, end == end, start
        if start < 1:
            start == 1
        if start < end:
            return start, end, self._test_normal
        else:
            return start, end, self._test_reverse

    def _test_normal(self, start, end, site):
        """A._test_normal(start, end, site) -> bool.

        Internal use only
        Test if site is in between start and end.
        """
        return start <= site < end

    def _test_reverse(self, start, end, site):
        """A._test_reverse(start, end, site) -> bool.

        Internal use only
        Test if site is in between end and start (for circular sequences).
        """
        return start <= site <= len(self.sequence) or 1 <= site < end

    def print_that(self, dct=None, title='', s1=''):
        """A.print_that([dct[, title[, s1]]]) -> print the results from dct.

        If dct is not given the full dictionary is used.
        """
        if not dct:
            dct = self.mapping
        print("")
        return PrintFormat.print_that(self, dct, title, s1)

    def change(self, **what):
        """A.change(**attribute_name) -> Change attribute of Analysis.

        It is possible to change the width of the shell by setting
        self.ConsoleWidth to what you want.
        self.NameWidth refer to the maximal length of the enzyme name.

        Changing one of these parameters here might not give the results
        you expect. In which case, you can settle back to a 80 columns shell
        or try to change self.Cmodulo and self.PrefWidth in PrintFormat until
        you get it right.
        """
        for k, v in what.items():
            if k in ('NameWidth', 'ConsoleWidth'):
                setattr(self, k, v)
                self.Cmodulo = self.ConsoleWidth % self.NameWidth
                self.PrefWidth = self.ConsoleWidth - self.Cmodulo
            elif k is 'sequence':
                setattr(self, 'sequence', v)
                self.search(self.sequence, self.linear)
            elif k is 'rb':
                self = Analysis.__init__(self, v, self.sequence, self.linear)
            elif k is 'linear':
                setattr(self, 'linear', v)
                self.search(self.sequence, v)
            elif k in ('Indent', 'Maxsize'):
                setattr(self, k, v)
            elif k in ('Cmodulo', 'PrefWidth'):
                raise AttributeError(
                    'To change %s, change NameWidth and/or ConsoleWidth'
                    % name)
            else:
                raise AttributeError(
                    'Analysis has no attribute %s' % name)
        return

    def full(self, linear=True):
        """A.full() -> dict.

        Full Restriction Map of the sequence.
        """
        return self.mapping

    def blunt(self, dct=None):
        """A.blunt([dct]) -> dict.

        Only the enzymes which have a 3'overhang restriction site.
        """
        if not dct:
            dct = self.mapping
        return dict((k, v) for k, v in dct.items() if k.is_blunt())

    def overhang5(self, dct=None):
        """A.overhang5([dct]) -> dict.

        Only the enzymes which have a 5' overhang restriction site.
        """
        if not dct:
            dct = self.mapping
        return dict((k, v) for k, v in dct.items() if k.is_5overhang())

    def overhang3(self, dct=None):
        """A.Overhang3([dct]) -> dict.

        Only the enzymes which have a 3'overhang restriction site.
        """
        if not dct:
            dct = self.mapping
        return dict((k, v) for k, v in dct.items() if k.is_3overhang())

    def defined(self, dct=None):
        """A.defined([dct]) -> dict.

        Only the enzymes that have a defined restriction site in Rebase.
        """
        if not dct:
            dct = self.mapping
        return dict((k, v) for k, v in dct.items() if k.is_defined())

    def with_sites(self, dct=None):
        """A.with_sites([dct]) -> dict.

        Enzymes which have at least one site in the sequence.
        """
        if not dct:
            dct = self.mapping
        return dict((k, v) for k, v in dct.items() if v)

    def without_site(self, dct=None):
        """A.without_site([dct]) -> dict.

        Enzymes which have no site in the sequence.
        """
        if not dct:
            dct = self.mapping
        return dict((k, v) for k, v in dct.items() if not v)

    def with_N_sites(self, N, dct=None):
        """A.With_N_Sites(N [, dct]) -> dict.

        Enzymes which cut N times the sequence.
        """
        if not dct:
            dct = self.mapping
        return dict((k, v) for k, v in dct.items()if len(v) == N)

    def with_number_list(self, list, dct=None):
        if not dct:
            dct = self.mapping
        return dict((k, v) for k, v in dct.items() if len(v) in list)

    def with_name(self, names, dct=None):
        """A.with_name(list_of_names [, dct]) ->

         Limit the search to the enzymes named in list_of_names.
         """
        for i, enzyme in enumerate(names):
            if enzyme not in AllEnzymes:
                print("no data for the enzyme: %s" % name)
                del names[i]
        if not dct:
            return RestrictionBatch(names).search(self.sequence)
        return dict((n, dct[n]) for n in names if n in dct)

    def with_site_size(self, site_size, dct=None):
        """A.with_site_size(site_size [, dct]) ->

         Limit the search to the enzymes whose site is of size <site_size>.
         """
        sites = [name for name in self if name.size == site_size]
        if not dct:
            return RestrictionBatch(sites).search(self.sequence)
        return dict((k, v) for k, v in dct.items() if k in site_size)

    def only_between(self, start, end, dct=None):
        """A.only_between(start, end[, dct]) -> dict.

        Enzymes that cut the sequence only in between start and end.
        """
        start, end, test = self._boundaries(start, end)
        if not dct:
            dct = self.mapping
        d = dict(dct)
        for key, sites in dct.items():
            if not sites:
                del d[key]
                continue
            for site in sites:
                if test(start, end, site):
                    continue
                else:
                    del d[key]
                    break
        return d

    def between(self, start, end, dct=None):
        """A.between(start, end [, dct]) -> dict.

        Enzymes that cut the sequence at least in between start and end.
        They may cut outside as well.
        """
        start, end, test = self._boundaries(start, end)
        d = {}
        if not dct:
            dct = self.mapping
        for key, sites in dct.items():
            for site in sites:
                if test(start, end, site):
                    d[key] = sites
                    break
                continue
        return d

    def show_only_between(self, start, end, dct=None):
        """A.show_only_between(start, end [, dct]) -> dict.

        Enzymes that cut the sequence outside of the region
        in between start and end but do not cut inside.
        """
        d = []
        if start <= end:
            d = [(k, [vv for vv in v if start <= vv <= end])
                 for v in self.between(start, end, dct)]
        else:
            d = [(k, [vv for vv in v if start <= vv or vv <= end])
                 for v in self.between(start, end, dct)]
        return dict(d)

    def only_outside(self, start, end, dct=None):
        """A.only_outside(start, end [, dct]) -> dict.

        Enzymes that cut the sequence outside of the region
        in between start and end but do not cut inside.
        """
        start, end, test = self._boundaries(start, end)
        if not dct:
            dct = self.mapping
        d = dict(dct)
        for key, sites in dct.items():
            if not sites:
                del d[key]
                continue
            for site in sites:
                if test(start, end, site):
                    del d[key]
                    break
                else:
                    continue
        return d

    def outside(self, start, end, dct=None):
        """A.outside((start, end [, dct]) -> dict.

        Enzymes that cut outside the region in between start and end.
        No test is made to know if they cut or not inside this region.
        """
        start, end, test = self._boundaries(start, end)
        if not dct:
            dct = self.mapping
        d = {}
        for key, sites in dct.items():
            for site in sites:
                if test(start, end, site):
                    continue
                else:
                    d[key] = sites
                    break
        return d

    def do_not_cut(self, start, end, dct=None):
        """A.do_not_cut(start, end [, dct]) -> dict.

        Enzymes that do not cut the region in between start and end.
        """
        if not dct:
            dct = self.mapping
        d = self.without_site()
        d.update(self.only_outside(start, end, dct))
        return d

#
#   The restriction enzyme classes are created dynamically when the module is
#   imported. Here is the magic which allow the creation of the
#   restriction-enzyme classes.
#
#   The reason for the two dictionaries in Restriction_Dictionary
#   one for the types (which will be called pseudo-type as they really
#   correspond to the values that instances of RestrictionType can take)
#   and one for the enzymes is efficiency as the bases are evaluated
#   once per pseudo-type.
#
#   However Restriction is still a very inefficient module at import. But
#   remember that around 660 classes (which is more or less the size of Rebase)
#   have to be created dynamically. However, this processing take place only
#   once.
#   This inefficiency is however largely compensated by the use of metaclass
#   which provide a very efficient layout for the class themselves mostly
#   alleviating the need of if/else loops in the class methods.
#
#   It is essential to run Restriction with doc string optimisation (-OO
#   switch) as the doc string of 660 classes take a lot of processing.
#
CommOnly = RestrictionBatch()    # commercial enzymes
NonComm = RestrictionBatch()     # not available commercially
for TYPE, (bases, enzymes) in typedict.items():
    #
    #   The keys are the pseudo-types TYPE (stored as type1, type2...)
    #   The names are not important and are only present to differentiate
    #   the keys in the dict. All the pseudo-types are in fact RestrictionType.
    #   These names will not be used after and the pseudo-types are not
    #   kept in the locals() dictionary. It is therefore impossible to
    #   import them.
    #   Now, if you have look at the dictionary, you will see that not all the
    #   types are present as those without corresponding enzymes have been
    #   removed by Dictionary_Builder().
    #
    #   The values are tuples which contain
    #   as first element a tuple of bases (as string) and
    #   as second element the names of the enzymes.
    #
    #   First eval the bases.
    #
    bases = tuple(eval(x) for x in bases)
    #
    #   now create the particular value of RestrictionType for the classes
    #   in enzymes.
    #
    T = type.__new__(RestrictionType, 'RestrictionType', bases, {})
    for k in enzymes:
        #
        #   Now, we go through all the enzymes and assign them their type.
        #   enzymedict[k] contains the values of the attributes for this
        #   particular class (self.site, self.ovhg,....).
        #
        newenz = T(k, bases, enzymedict[k])
        #
        #   we add the enzymes to the corresponding batch.
        #
        #   No need to verify the enzyme is a RestrictionType -> add_nocheck
        #
        if newenz.is_comm():
            CommOnly.add_nocheck(newenz)
        else:
            NonComm.add_nocheck(newenz)
#
#   AllEnzymes is a RestrictionBatch with all the enzymes from Rebase.
#
AllEnzymes = CommOnly | NonComm
#
#   Now, place the enzymes in locals so they can be imported.
#
names = [str(x) for x in AllEnzymes]
try:
    del x
except NameError:
    # Scoping changed in Python 3, the variable isn't leaked
    pass
locals().update(dict(zip(names, AllEnzymes)))
__all__ = ['FormattedSeq', 'Analysis', 'RestrictionBatch', 'AllEnzymes',
           'CommOnly', 'NonComm'] + names
del k, enzymes, TYPE, bases, names