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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
#!/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
        -----------------------------------------------------------------------

"""


import warnings

import re
import string
import itertools

from Bio.Seq import Seq, MutableSeq
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
from Bio.Restriction.PrintFormat import PrintFormat
from Bio import BiopythonWarning


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:
    """A linear or circular sequence object for restriction analysis.

    Translates 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.
    """

    _remove_chars = string.whitespace.encode() + string.digits.encode()
    _table = bytearray(256)
    upper_to_lower = ord("A") - ord("a")
    for c in b"ABCDGHKMNRSTVWY":  # Only allow IUPAC letters
        _table[c] = c  # map uppercase to uppercase
        _table[c - upper_to_lower] = c  # map lowercase to uppercase
    del upper_to_lower
    _table = bytes(_table)

    def __init__(self, seq, linear=True):
        """Initialize ``FormattedSeq`` with sequence and topology (optional).

        ``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)):
            self.lower = seq.islower()
            data = bytes(seq)
            self.data = data.translate(self._table, delete=self._remove_chars)
            if 0 in self.data:  # Check if all letters were IUPAC
                raise TypeError(f"Invalid character found in {data.decode()}")
            # Note this adds a leading space to the sequence (!)
            self.data = " " + self.data.decode("ASCII")
            self.linear = linear
            self.klass = seq.__class__
        elif isinstance(seq, FormattedSeq):
            self.lower = seq.lower
            self.data = seq.data
            self.linear = seq.linear
            self.klass = seq.klass
        else:
            raise TypeError(f"expected Seq or MutableSeq, got {type(seq)}")

    def __len__(self):
        """Return length of ``FormattedSeq``.

        ``FormattedSeq`` has a leading space, thus subtract 1.
        """
        return len(self.data) - 1

    def __repr__(self):
        """Represent ``FormattedSeq`` class as a string."""
        return f"FormattedSeq({self[1:]!r}, linear={self.linear!r})"

    def __eq__(self, other):
        """Implement equality operator for ``FormattedSeq`` object."""
        if isinstance(other, FormattedSeq):
            if repr(self) == repr(other):
                return True
            else:
                return False
        return False

    def circularise(self):
        """Circularise sequence in place."""
        self.linear = False

    def linearise(self):
        """Linearise sequence in place."""
        self.linear = True

    def to_linear(self):
        """Make a new instance of sequence as linear."""
        new = self.__class__(self)
        new.linear = True
        return new

    def to_circular(self):
        """Make a new instance of sequence as circular."""
        new = self.__class__(self)
        new.linear = False
        return new

    def is_linear(self):
        """Return if sequence is linear (True) or circular (False)."""
        return self.linear

    def finditer(self, pattern, size):
        """Return a list of a given pattern which occurs in 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):
        """Return substring of ``FormattedSeq``.

        The class of the returned object is the class of the respective
        sequence. Note that due to the leading space, indexing is 1-based:

        >>> from Bio.Seq import Seq
        >>> from Bio.Restriction.Restriction import FormattedSeq
        >>> f_seq = FormattedSeq(Seq('ATGCATGC'))
        >>> f_seq[1]
        Seq('A')

        """
        if self.lower:
            return self.klass(self.data[i].lower())
        return self.klass(self.data[i])


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

    Implement the operator methods.
    """

    def __init__(cls, name="", bases=(), dct=None):
        """Initialize 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(f"Problem with hyphen in {name!r} as enzyme name")
        # 2011/11/26 - Nobody knows what this call was supposed to accomplish,
        # but all unit tests seem to pass without it.
        # super().__init__(cls, name, bases, dct)
        try:
            cls.compsite = re.compile(cls.compsite)
        except AttributeError:
            # Can happen if initialised wrongly.
            # (This was seen when Sphinx api-doc imports the classes, and
            # tried to automatically general documentation for them)
            pass
        except Exception:
            raise ValueError(
                f"Problem with regular expression, re.compiled({cls.compsite!r})"
            ) from None

    def __add__(cls, other):
        """Add restriction enzyme to a 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 __truediv__(cls, other):
        """Override '/' operator to use as search method.

        >>> from Bio.Restriction import EcoRI
        >>> EcoRI/Seq('GAATTC')
        [2]

        Returns RE.search(other).
        """
        return cls.search(other)

    def __rtruediv__(cls, other):
        """Override division with reversed operands to use as search method.

        >>> from Bio.Restriction import EcoRI
        >>> Seq('GAATTC')/EcoRI
        [2]

        Returns RE.search(other).
        """
        return cls.search(other)

    def __floordiv__(cls, other):
        """Override '//' operator to use as catalyse method.

        >>> from Bio.Restriction import EcoRI
        >>> EcoRI//Seq('GAATTC')
        (Seq('G'), Seq('AATTC'))

        Returns RE.catalyse(other).
        """
        return cls.catalyse(other)

    def __rfloordiv__(cls, other):
        """As __floordiv__, with reversed operands.

        >>> from Bio.Restriction import EcoRI
        >>> Seq('GAATTC')//EcoRI
        (Seq('G'), Seq('AATTC'))

        Returns RE.catalyse(other).
        """
        return cls.catalyse(other)

    def __str__(cls):
        """Return the name of the enzyme as string."""
        return cls.__name__

    def __repr__(cls):
        """Implement repr method.

        Used with eval or exec will instantiate the enzyme.
        """
        return f"{cls.__name__}"

    def __len__(cls):
        """Return length of recognition site of enzyme as int."""
        try:
            return cls.size
        except AttributeError:
            # Happens if the instance was not initialised as expected.
            # e.g. if instance created by a documentation framework
            # like Sphinx trying to inspect the class automatically,
            # Also seen within IPython.
            return 0

    def __hash__(cls):
        """Implement ``hash()`` method for ``RestrictionType``.

        Python default is to use ``id(...)``
        This is consistent with the ``__eq__`` implementation
        """
        return id(cls)

    def __eq__(cls, other):
        """Override '==' operator.

        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):
        """Override '!=' operator.

        Isoschizomer strict (same recognition site, same restriction) -> False
        All the other-> True

        WARNING - This is not the inverse of the __eq__ method

        >>> from Bio.Restriction import SacI, SstI
        >>> SacI != SstI  # true isoschizomers
        False
        >>> SacI == SstI
        False
        """
        if not isinstance(other, RestrictionType):
            return True
        elif cls.charac == other.charac:
            return False
        else:
            return True

    def __rshift__(cls, other):
        """Override '>>' operator to test for neoschizomers.

        neoschizomer : same recognition site, different restriction. -> True
        all the others :                                             -> False

        >>> from Bio.Restriction import SmaI, XmaI
        >>> SmaI >> XmaI
        True
        """
        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):
        """Override '%' operator to test for compatible overhangs.

        True if a and b have compatible overhang.

        >>> from Bio.Restriction import XhoI, SalI
        >>> XhoI % SalI
        True
        """
        if not isinstance(other, RestrictionType):
            raise TypeError(f"expected RestrictionType, got {type(other)} instead")
        return cls._mod1(other)

    def __ge__(cls, other):
        """Compare length of recognition site of two enzymes.

        Override '>='. 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.

        >>> from Bio.Restriction import EcoRI, EcoRV
        >>> EcoRI.size
        6
        >>> EcoRV.size
        6
        >>> EcoRI >= EcoRV
        False
        """
        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):
        """Compare length of recognition site of two enzymes.

        Override '>'. 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):
        """Compare length of recognition site of two enzymes.

        Override '<='. 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):
        """Compare length of recognition site of two enzymes.

        Override '<'. 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 instantiated.
    """

    @classmethod
    def search(cls, dna, linear=True):
        """Return a list of cutting sites of the enzyme in the sequence.

        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 that 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):
        """Print all the suppliers of restriction enzyme."""
        supply = sorted(x[0] for x in suppliers_dict.values())
        print(",\n".join(supply))

    @classmethod
    def is_equischizomer(cls, other):
        """Test for real isoschizomer.

        True if other is an isoschizomer of RE, but not an neoschizomer,
        else False.

        Equischizomer: same site, same position of restriction.

        >>> from Bio.Restriction import SacI, SstI, SmaI, XmaI
        >>> SacI.is_equischizomer(SstI)
        True
        >>> SmaI.is_equischizomer(XmaI)
        False

        """
        return not cls != other

    @classmethod
    def is_neoschizomer(cls, other):
        """Test for neoschizomer.

        True if other is an isoschizomer of RE, else False.
        Neoschizomer: same site, different position of restriction.
        """
        return cls >> other

    @classmethod
    def is_isoschizomer(cls, other):
        """Test for same recognition site.

        True if other has the same recognition site, else False.

        Isoschizomer: same site.

        >>> from Bio.Restriction import SacI, SstI, SmaI, XmaI
        >>> SacI.is_isoschizomer(SstI)
        True
        >>> SmaI.is_isoschizomer(XmaI)
        True

        """
        return (not cls != other) or cls >> other

    @classmethod
    def equischizomers(cls, batch=None):
        """List equischizomers of the enzyme.

        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):
        """List neoschizomers of the enzyme.

        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):
        """List all isoschizomers of the enzyme.

        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):
        """Return the theoretically cutting frequency of the enzyme.

        Frequency of the site, given as 'one cut per x bases' (int).
        """
        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 unknown 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):
        """Return if the cutting pattern has one cut.

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

    @classmethod
    def cut_twice(cls):
        """Return if the cutting pattern has two cuts.

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

    @classmethod
    def _modify(cls, location):
        """Return a generator that moves the cutting position by 1 (PRIVATE).

        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):
        """Return a generator that moves the cutting position by 1 (PRIVATE).

        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):
        """Return a list of the enzyme's characteristics as 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 for 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):
        """Return if the cutting pattern has one cut.

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

    @classmethod
    def cut_twice(cls):
        """Return if the cutting pattern has two cuts.

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

    @classmethod
    def _modify(cls, location):
        """Return a generator that moves the cutting position by 1 (PRIVATE).

        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):
        """Return a generator that moves the cutting position by 1 (PRIVATE).

        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):
        """Return a list of the enzyme's characteristics as 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 for 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):
        """Return if the cutting pattern has one cut.

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

    @classmethod
    def cut_twice(cls):
        """Return if the cutting pattern has two cuts.

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

    @classmethod
    def _modify(cls, location):
        """Return a generator that moves the cutting position by 1 (PRIVATE).

        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):
        """Return a generator that moves the cutting position by 1 (PRIVATE).

        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):
        """Return a list of the enzyme's characteristics as 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):
        """Return if recognition site can be methylated.

        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):
        """Return if recognition site can be methylated.

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


class Palindromic(AbstractCut):
    """Implement methods for enzymes with palindromic recognition sites.

    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):
        """Return a list of cutting sites of the enzyme in the sequence (PRIVATE).

        For internal use only.

        Implement the search method for palindromic enzymes.
        """
        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):
        """Return if the enzyme has a palindromic recoginition site."""
        return True


class NonPalindromic(AbstractCut):
    """Implement methods for enzymes with non-palindromic recognition sites.

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

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

    @classmethod
    def _search(cls):
        """Return a list of cutting sites of the enzyme in the sequence (PRIVATE).

        For internal use only.

        Implement the search method for non palindromic enzymes.
        """
        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 += list(modif(start))
            else:
                cls.on_minus += list(revmodif(start))
        cls.results += cls.on_minus

        if cls.results:
            cls.results.sort()
            cls._drop()
        return cls.results

    @classmethod
    def is_palindromic(cls):
        """Return if the enzyme has a palindromic recoginition site."""
        return False


class Unknown(AbstractCut):
    """Implement methods for enzymes that produce unknown overhangs.

    These enzymes are also NotDefined and NoCut.

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

    @classmethod
    def catalyse(cls, dna, linear=True):
        """List the sequence fragments after cutting dna with enzyme.

        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(f"{cls.__name__} restriction is unknown.")

    catalyze = catalyse

    @classmethod
    def is_blunt(cls):
        """Return if the enzyme produces blunt ends.

        True if the enzyme produces blunt end.

        Related methods:

        - RE.is_3overhang()
        - RE.is_5overhang()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def is_5overhang(cls):
        """Return if the enzymes produces 5' overhanging ends.

        True if the enzyme produces 5' overhang sticky end.

        Related methods:

        - RE.is_3overhang()
        - RE.is_blunt()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def is_3overhang(cls):
        """Return if the enzyme produces 3' overhanging ends.

        True if the enzyme produces 3' overhang sticky end.

        Related methods:

        - RE.is_5overhang()
        - RE.is_blunt()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def overhang(cls):
        """Return the type of the enzyme's overhang as string.

        Can be "3' overhang", "5' overhang", "blunt", "unknown".
        """
        return "unknown"

    @classmethod
    def compatible_end(cls):
        """List all enzymes that produce compatible ends for the enzyme."""
        return []

    @classmethod
    def _mod1(cls, other):
        """Test if other enzyme produces compatible ends for enzyme (PRIVATE).

        For internal use only.

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


class Blunt(AbstractCut):
    """Implement methods for enzymes that produce blunt ends.

    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):
        """List the sequence fragments after cutting dna with enzyme.

        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):
        """Return if the enzyme produces blunt ends.

        True if the enzyme produces blunt end.

        Related methods:

        - RE.is_3overhang()
        - RE.is_5overhang()
        - RE.is_unknown()

        """
        return True

    @classmethod
    def is_5overhang(cls):
        """Return if the enzymes produces 5' overhanging ends.

        True if the enzyme produces 5' overhang sticky end.

        Related methods:

        - RE.is_3overhang()
        - RE.is_blunt()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def is_3overhang(cls):
        """Return if the enzyme produces 3' overhanging ends.

        True if the enzyme produces 3' overhang sticky end.

        Related methods:

        - RE.is_5overhang()
        - RE.is_blunt()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def overhang(cls):
        """Return the type of the enzyme's overhang as string.

        Can be "3' overhang", "5' overhang", "blunt", "unknown".
        """
        return "blunt"

    @classmethod
    def compatible_end(cls, batch=None):
        """List all enzymes that produce compatible ends for the enzyme."""
        if not batch:
            batch = AllEnzymes
        r = sorted(x for x in iter(AllEnzymes) if x.is_blunt())
        return r

    @staticmethod
    def _mod1(other):
        """Test if other enzyme produces compatible ends for enzyme (PRIVATE).

        For internal use only

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


class Ov5(AbstractCut):
    """Implement methods for enzymes that produce 5' overhanging ends.

    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):
        """List the sequence fragments after cutting dna with enzyme.

        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):
        """Return if the enzyme produces blunt ends.

        True if the enzyme produces blunt end.

        Related methods:

        - RE.is_3overhang()
        - RE.is_5overhang()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def is_5overhang(cls):
        """Return if the enzymes produces 5' overhanging ends.

        True if the enzyme produces 5' overhang sticky end.

        Related methods:

        - RE.is_3overhang()
        - RE.is_blunt()
        - RE.is_unknown()

        """
        return True

    @classmethod
    def is_3overhang(cls):
        """Return if the enzyme produces 3' overhanging ends.

        True if the enzyme produces 3' overhang sticky end.

        Related methods:

        - RE.is_5overhang()
        - RE.is_blunt()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def overhang(cls):
        """Return the type of the enzyme's overhang as string.

        Can be "3' overhang", "5' overhang", "blunt", "unknown".
        """
        return "5' overhang"

    @classmethod
    def compatible_end(cls, batch=None):
        """List all enzymes that produce compatible ends for the enzyme."""
        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):
        """Test if other enzyme produces compatible ends for enzyme (PRIVATE).

        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 methods for enzymes that produce 3' overhanging ends.

    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):
        """List the sequence fragments after cutting dna with enzyme.

        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):
        """Return if the enzyme produces blunt ends.

        True if the enzyme produces blunt end.

        Related methods:

        - RE.is_3overhang()
        - RE.is_5overhang()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def is_5overhang(cls):
        """Return if the enzymes produces 5' overhanging ends.

        True if the enzyme produces 5' overhang sticky end.

        Related methods:

        - RE.is_3overhang()
        - RE.is_blunt()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def is_3overhang(cls):
        """Return if the enzyme produces 3' overhanging ends.

        True if the enzyme produces 3' overhang sticky end.

        Related methods:

        - RE.is_5overhang()
        - RE.is_blunt()
        - RE.is_unknown()

        """
        return True

    @classmethod
    def overhang(cls):
        """Return the type of the enzyme's overhang as string.

        Can be "3' overhang", "5' overhang", "blunt", "unknown".
        """
        return "3' overhang"

    @classmethod
    def compatible_end(cls, batch=None):
        """List all enzymes that produce compatible ends for the enzyme."""
        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):
        """Test if other enzyme produces compatible ends for enzyme (PRIVATE).

        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 methods for enzymes with defined recognition site and cut.

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

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

    @classmethod
    def _drop(cls):
        """Remove cuts that are outsite of the sequence (PRIVATE).

        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 = list(drop(lambda x: x <= 1, cls.results))
            cls.results = list(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

    @classmethod
    def is_defined(cls):
        """Return if recognition sequence and cut are defined.

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

        Related methods:

        - RE.is_ambiguous()
        - RE.is_unknown()

        """
        return True

    @classmethod
    def is_ambiguous(cls):
        """Return if recognition sequence and cut may be ambiguous.

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

        Related methods:

        - RE.is_defined()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def is_unknown(cls):
        """Return if recognition sequence is unknown.

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

        Related methods:

        - RE.is_defined()
        - RE.is_ambiguous()

        """
        return False

    @classmethod
    def elucidate(cls):
        """Return a string representing the recognition site and cuttings.

        Return a representation of the site with the cut on the (+) strand
        represented as '^' and the cut on the (-) strand as '_'.
        ie:

        >>> from Bio.Restriction import EcoRI, KpnI, EcoRV, SnaI
        >>> 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):
        """Test if other enzyme produces compatible ends for enzyme (PRIVATE).

        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 methods for enzymes that produce variable overhangs.

    Typical example : BstXI -> CCAN_NNNN^NTGG
                      The overhang can be any sequence of 4 bases.

    Notes:
        Blunt enzymes are always defined. Even if their site is GGATCCNNN^_N
        Their overhang is always the same : blunt!

    Internal use only. Not meant to be instantiated.

    """

    @classmethod
    def _drop(cls):
        """Remove cuts that are outsite of the sequence (PRIVATE).

        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 = list(drop(lambda x: x <= 1, cls.results))
            cls.results = list(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

    @classmethod
    def is_defined(cls):
        """Return if recognition sequence and cut are defined.

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

        Related methods:

        - RE.is_ambiguous()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def is_ambiguous(cls):
        """Return if recognition sequence and cut may be ambiguous.

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

        Related methods:

        - RE.is_defined()
        - RE.is_unknown()

        """
        return True

    @classmethod
    def is_unknown(cls):
        """Return if recognition sequence is unknown.

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

        Related methods:

        - RE.is_defined()
        - RE.is_ambiguous()

        """
        return False

    @classmethod
    def _mod2(cls, other):
        """Test if other enzyme produces compatible ends for enzyme (PRIVATE).

        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):
        """Return a string representing the recognition site and cuttings.

        Return a representation of the site with the cut on the (+) strand
        represented as '^' and the cut on the (-) strand as '_'.
        ie:

        >>> from Bio.Restriction import EcoRI, KpnI, EcoRV, SnaI
        >>> 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 methods for enzymes with non-characterized overhangs.

    Correspond to NoCut and Unknown.

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

    @classmethod
    def _drop(cls):
        """Remove cuts that are outsite of the sequence (PRIVATE).

        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

    @classmethod
    def is_defined(cls):
        """Return if recognition sequence and cut are defined.

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

        Related methods:

        - RE.is_ambiguous()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def is_ambiguous(cls):
        """Return if recognition sequence and cut may be ambiguous.

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

        Related methods:

        - RE.is_defined()
        - RE.is_unknown()

        """
        return False

    @classmethod
    def is_unknown(cls):
        """Return if recognition sequence is unknown.

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

        Related methods:

        - RE.is_defined()
        - RE.is_ambiguous()

        """
        return True

    @classmethod
    def _mod2(cls, other):
        """Test if other enzyme produces compatible ends for enzyme (PRIVATE).

        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):
        """Return a string representing the recognition site and cuttings.

        Return a representation of the site with the cut on the (+) strand
        represented as '^' and the cut on the (-) strand as '_'.
        ie:

        >>> from Bio.Restriction import EcoRI, KpnI, EcoRV, SnaI
        >>> 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 f"? {cls.site} ?"


class Commercially_available(AbstractCut):
    """Implement methods for enzymes which are commercially available.

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

    #
    #   Recent addition to Rebase make this naming convention uncertain.
    #   May be better to says enzymes which have a supplier.
    #

    @classmethod
    def suppliers(cls):
        """Print a list of suppliers of the enzyme."""
        for s in cls.suppl:
            print(suppliers_dict[s][0] + ",")

    @classmethod
    def supplier_list(cls):
        """Return a list of suppliers of the enzyme."""
        return [v[0] for k, v in suppliers_dict.items() if k in cls.suppl]

    @classmethod
    def buffers(cls, supplier):
        """Return the recommended buffer of the supplier for this enzyme.

        Not implemented yet.
        """

    @classmethod
    def is_comm(cls):
        """Return if enzyme is commercially available.

        True if RE has suppliers.
        """
        return True


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

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

    @staticmethod
    def suppliers():
        """Print a list of suppliers of the enzyme."""
        return None

    @classmethod
    def supplier_list(cls):
        """Return a list of suppliers of the enzyme."""
        return []

    @classmethod
    def buffers(cls, supplier):
        """Return the recommended buffer of the supplier for this enzyme.

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

    @classmethod
    def is_comm(cls):
        """Return if enzyme is commercially available.

        True if RE has suppliers.
        """
        return False


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


class RestrictionBatch(set):
    """Class for operations on more than one enzyme."""

    def __init__(self, first=(), suppliers=()):
        """Initialize empty RB or pre-fill with enzymes (from supplier)."""
        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
        self.suppliers = [x for x in suppliers if x in suppliers_dict]

    def __str__(self):
        """Return a readable representation of the ``RestrictionBatch``."""
        if len(self) < 5:
            return "+".join(self.elements())
        else:
            return "...".join(
                ("+".join(self.elements()[:2]), "+".join(self.elements()[-2:]))
            )

    def __repr__(self):
        """Represent ``RestrictionBatch`` class as a string for debugging."""
        return f"RestrictionBatch({self.elements()})"

    def __contains__(self, other):
        """Implement ``in`` for ``RestrictionBatch``."""
        try:
            other = self.format(other)
        except ValueError:  # other is not a restriction enzyme
            return False
        return set.__contains__(self, other)

    def __div__(self, other):
        """Override '/' operator to use as search method."""
        return self.search(other)

    def __rdiv__(self, other):
        """Override division with reversed operands to use as search method."""
        return self.search(other)

    def __truediv__(self, other):
        """Override Python 3 division operator to use as search method.

        Like __div__.
        """
        return self.search(other)

    def __rtruediv__(self, other):
        """As __truediv___, with reversed operands.

        Like __rdiv__.
        """
        return self.search(other)

    def get(self, enzyme, add=False):
        """Check if enzyme is in batch and return it.

        If add is True and enzyme is not in batch add enzyme to batch.
        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(f"enzyme {e.__name__} is not in RestrictionBatch")

    def lambdasplit(self, func):
        """Filter enzymes in batch with supplied function.

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

    def add_supplier(self, letter):
        """Add all enzymes from a given supplier to batch.

        letter represents the suppliers as defined in the dictionary
        RestrictionDictionary.suppliers
        Returns 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))

    def current_suppliers(self):
        """List the current suppliers for the restriction batch.

        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):
        """Override '+=' for use with sets.

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

    def __add__(self, other):
        """Override '+' for use with sets.

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

    def remove(self, other):
        """Remove enzyme from restriction batch.

        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):
        """Add a restriction enzyme to the restriction batch.

        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):
        """Add restriction enzyme to batch without checking its type."""
        return set.add(self, other)

    def format(self, y):
        """Evaluate enzyme (name) and return it (as RestrictionType).

        If y is a RestrictionType return y.
        If y can be evaluated to a RestrictionType return eval(y).
        Raise a ValueError in all other case.
        """
        try:
            if isinstance(y, RestrictionType):
                return y
            elif isinstance(eval(str(y)), RestrictionType):
                return eval(y)
        except (NameError, SyntaxError):
            pass
        raise ValueError(f"{y.__class__} is not a RestrictionType")

    def is_restriction(self, y):
        """Return if enzyme (name) is a known enzyme.

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

    def split(self, *classes, **bool):
        """Extract enzymes of a certain class and put in 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 = list(filter(splittest, self))
        new = RestrictionBatch()
        new._data = dict(zip(d, [True] * len(d)))
        return new

    def elements(self):
        """List the enzymes of the RestrictionBatch as list of strings.

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

    def as_string(self):
        """List the names of the enzymes of the RestrictionBatch.

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

    @classmethod
    def suppl_codes(cls):
        """Return a dictionary with supplier codes.

        Letter code for the suppliers.
        """
        supply = {k: v[0] for k, v in suppliers_dict.items()}
        return supply

    @classmethod
    def show_codes(cls):
        """Print a list of supplier codes."""
        supply = [" = ".join(i) for i in cls.suppl_codes().items()]
        print("\n".join(supply))

    def search(self, dna, linear=True):
        """Return a dic of cutting sites in the seq for the batch enzymes."""
        #
        #   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 = {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 = {x: x.search(dna) for x in self}
                return self.mapping
        raise TypeError(f"Expected Seq or MutableSeq instance, got {type(dna)} instead")


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

_empty_DNA = DNA("")
_restrictionbatch = RestrictionBatch()


class Analysis(RestrictionBatch, PrintFormat):
    """Provide methods for enhanced analysis and pretty printing."""

    def __init__(
        self, restrictionbatch=_restrictionbatch, sequence=_empty_DNA, linear=True
    ):
        """Initialize an Analysis with RestrictionBatch and sequence.

        For most of the methods 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 RestrictionBatch
        which has been given when the Analysis class has been instantiated,
        will be carried out and used.
        """
        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):
        """Represent ``Analysis`` class as a string."""
        return f"Analysis({self.rb!r},{self.sequence!r},{self.linear})"

    def _sub_set(self, wanted):
        """Filter result for keys which are in wanted (PRIVATE).

        Internal use only. Returns a dict.

        Screen the results through wanted set.
        Keep only the results for which the enzymes is in wanted set.
        """
        # It seems that this method is not used in the whole class!
        return {k: v for k, v in self.mapping.items() if k in wanted}

    def _boundaries(self, start, end):
        """Set boundaries to correct values (PRIVATE).

        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(f"expected int, got {type(start)} instead")
        if not isinstance(end, int):
            raise TypeError(f"expected int, got {type(end)} instead")
        if start < 1:  # Looks like this tries to do python list like indexing
            start += len(self.sequence)
        if end < 1:
            end += len(self.sequence)
        if start < end:
            pass
        else:
            start, end = end, start
        if start < end:
            return start, end, self._test_normal

    def _test_normal(self, start, end, site):
        """Test if site is between start and end (PRIVATE).

        Internal use only
        """
        return start <= site < end

    def _test_reverse(self, start, end, site):
        """Test if site is between end and start, for circular sequences (PRIVATE).

        Internal use only.
        """
        return start <= site <= len(self.sequence) or 1 <= site < end

    def format_output(self, dct=None, title="", s1=""):
        """Collect data and pass to PrintFormat.

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

    def print_that(self, dct=None, title="", s1=""):
        """Print the output of the analysis.

        If dct is not given the full dictionary is used.
        s1: Title for non-cutting enzymes
        This method prints the output of A.format_output() and it is here
        for backwards compatibility.
        """
        print(self.format_output(dct, title, s1))

    def change(self, **what):
        """Change parameters of print output.

        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 == "sequence":
                setattr(self, "sequence", v)
                self.search(self.sequence, self.linear)
            elif k == "rb":
                self = Analysis.__init__(self, v, self.sequence, self.linear)
            elif k == "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(
                    f"To change {k}, change NameWidth and/or ConsoleWidth"
                )
            else:
                raise AttributeError(f"Analysis has no attribute {k}")

    def full(self, linear=True):
        """Perform analysis with all enzymes of batch and return all results.

        Full Restriction Map of the sequence, as a dictionary.
        """
        return self.mapping

    def blunt(self, dct=None):
        """Return only cuts that have blunt ends."""
        if not dct:
            dct = self.mapping
        return {k: v for k, v in dct.items() if k.is_blunt()}

    def overhang5(self, dct=None):
        """Return only cuts that have 5' overhangs."""
        if not dct:
            dct = self.mapping
        return {k: v for k, v in dct.items() if k.is_5overhang()}

    def overhang3(self, dct=None):
        """Return only cuts that have 3' overhangs."""
        if not dct:
            dct = self.mapping
        return {k: v for k, v in dct.items() if k.is_3overhang()}

    def defined(self, dct=None):
        """Return only results from enzymes that produce defined overhangs."""
        if not dct:
            dct = self.mapping
        return {k: v for k, v in dct.items() if k.is_defined()}

    def with_sites(self, dct=None):
        """Return only results from enzyme with at least one cut."""
        if not dct:
            dct = self.mapping
        return {k: v for k, v in dct.items() if v}

    def without_site(self, dct=None):
        """Return only results from enzymes that don't cut the sequence."""
        if not dct:
            dct = self.mapping
        return {k: v for k, v in dct.items() if not v}

    def with_N_sites(self, N, dct=None):
        """Return only results from enzymes that cut the sequence N times."""
        if not dct:
            dct = self.mapping
        return {k: v for k, v in dct.items() if len(v) == N}

    def with_number_list(self, list, dct=None):
        """Return only results from enzymes that cut (x,y,z,...) times."""
        if not dct:
            dct = self.mapping
        return {k: v for k, v in dct.items() if len(v) in list}

    def with_name(self, names, dct=None):
        """Return only results from enzymes which names are listed."""
        for i, enzyme in enumerate(names):
            if enzyme not in AllEnzymes:
                warnings.warn(f"no data for the enzyme: {enzyme}", BiopythonWarning)
                del names[i]
        if not dct:
            return RestrictionBatch(names).search(self.sequence, self.linear)
        return {n: dct[n] for n in names if n in dct}

    def with_site_size(self, site_size, dct=None):
        """Return only results form enzymes with a given site size."""
        sites = [name for name in self if name.size == site_size]
        if not dct:
            return RestrictionBatch(sites).search(self.sequence)
        return {k: v for k, v in dct.items() if k in site_size}

    def only_between(self, start, end, dct=None):
        """Return only results from enzymes that only cut within start, 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):
        """Return only results from enzymes that cut at least within borders.

        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):
        """Return only results from within start, end.

        Enzymes must cut inside start/end and may also cut outside. However,
        only the cutting positions within start/end will be returned.
        """
        d = []
        if start <= end:
            d = [
                (k, [vv for vv in v if start <= vv <= end])
                for k, v in self.between(start, end, dct).items()
            ]
        else:
            d = [
                (k, [vv for vv in v if start <= vv or vv <= end])
                for k, v in self.between(start, end, dct).items()
            ]
        return dict(d)

    def only_outside(self, start, end, dct=None):
        """Return only results from enzymes that only cut outside start, end.

        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):
        """Return only results from enzymes that at least cut outside borders.

        Enzymes that cut outside the region in between start and end.
        They may cut inside as well.
        """
        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):
        """Return only results from enzymes that don't cut between borders."""
        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 = RestrictionBatch(CommOnly)
AllEnzymes.update(NonComm)
#
#   Now, place the enzymes in locals so they can be imported.
#
names = [str(x) for x in AllEnzymes]
locals().update(dict(zip(names, AllEnzymes)))
__all__ = (
    "FormattedSeq",
    "Analysis",
    "RestrictionBatch",
    "AllEnzymes",
    "CommOnly",
    "NonComm",
) + tuple(names)
del k, enzymes, TYPE, bases, names