File: __init__.py

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


__copyright__ = "Copyright (C) 2009-2013 Andreas Kloeckner"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""


from functools import reduce, wraps
import operator
import sys
import logging
from typing import (
        Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, TypeVar)
import builtins


from sys import intern


from decorator import decorator as my_decorator

# These are deprecated and will go away in 2022.
all = builtins.all
any = builtins.any


__doc__ = """
A Collection of Utilities
=========================

Math
----

.. autofunction:: levi_civita
.. autofunction:: perm
.. autofunction:: comb

Assertive accessors
-------------------

.. autofunction:: one
.. autofunction:: is_single_valued
.. autofunction:: all_roughly_equal
.. autofunction:: single_valued

Memoization
-----------

.. autofunction:: memoize
.. autofunction:: memoize_on_first_arg
.. autofunction:: memoize_method
.. autofunction:: memoize_in
.. autofunction:: keyed_memoize_on_first_arg
.. autofunction:: keyed_memoize_method

Argmin/max
----------

.. autofunction:: argmin2
.. autofunction:: argmax2
.. autofunction:: argmin
.. autofunction:: argmax

Cartesian products
------------------
.. autofunction:: cartesian_product
.. autofunction:: distinct_pairs

Permutations, Tuples, Integer sequences
---------------------------------------

.. autofunction:: wandering_element
.. autofunction:: generate_nonnegative_integer_tuples_below
.. autofunction:: generate_nonnegative_integer_tuples_summing_to_at_most
.. autofunction:: generate_all_nonnegative_integer_tuples
.. autofunction:: generate_all_integer_tuples_below
.. autofunction:: generate_all_integer_tuples
.. autofunction:: generate_permutations
.. autofunction:: generate_unique_permutations

Formatting
----------

.. autoclass:: Table
.. autofunction:: string_histogram
.. autofunction:: word_wrap

Debugging
---------

.. autofunction:: typedump
.. autofunction:: invoke_editor

Progress bars
-------------

.. autoclass:: ProgressBar

Name generation
---------------

.. autofunction:: generate_unique_names
.. autofunction:: generate_numbered_unique_names
.. autoclass:: UniqueNameGenerator

Deprecation Warnings
--------------------

.. autofunction:: deprecate_keyword

Functions for dealing with (large) auxiliary files
--------------------------------------------------

.. autofunction:: download_from_web_if_not_present

Helpers for :mod:`numpy`
------------------------

.. autofunction:: reshaped_view


Timing data
-----------

.. data:: SUPPORTS_PROCESS_TIME

   A :class:`bool` indicating whether :class:`ProcessTimer` measures elapsed
   process time (available on Python 3.3+).

.. autoclass:: ProcessTimer

Log utilities
-------------

.. autoclass:: ProcessLogger
.. autoclass:: DebugProcessLogger
.. autoclass:: log_process

Sorting in natural order
------------------------

.. autofunction:: natorder
.. autofunction:: natsorted

Type Variables Used
-------------------

.. class:: T

    Any type.

.. class:: F

    Any callable.
"""

# {{{ type variables

T = TypeVar("T")
F = TypeVar("F", bound=Callable[..., Any])

# }}}


# {{{ code maintenance

class MovedFunctionDeprecationWrapper:
    def __init__(self, f, deadline=None):
        if deadline is None:
            deadline = "the future"

        self.f = f
        self.deadline = deadline

    def __call__(self, *args, **kwargs):
        from warnings import warn
        warn(f"This function is deprecated and will go away in {self.deadline}. "
            f"Use {self.f.__module__}.{self.f.__name__} instead.",
            DeprecationWarning, stacklevel=2)

        return self.f(*args, **kwargs)


def deprecate_keyword(oldkey: str,
        newkey: Optional[str] = None, *,
        deadline: Optional[str] = None):
    """Decorator used to deprecate function keyword arguments.

    :arg oldkey: deprecated argument name.
    :arg newkey: new argument name that serves the same purpose, if any.
    :arg deadline: expected time frame for the removal of the deprecated argument.
    """
    from warnings import warn

    if deadline is None:
        deadline = "the future"

    def wrapper(func):
        @wraps(func)
        def inner_wrapper(*args, **kwargs):
            if oldkey in kwargs:
                if newkey is None:
                    warn(f"The '{oldkey}' keyword is deprecated and will "
                            f"go away in {deadline}.",
                            DeprecationWarning, stacklevel=2)
                else:
                    warn(f"The '{oldkey}' keyword is deprecated and will "
                            f"go away in {deadline}. "
                            f"Use '{newkey}' instead.",
                            DeprecationWarning, stacklevel=2)

                    if newkey in kwargs:
                        raise ValueError(f"Cannot use '{oldkey}' "
                                f"and '{newkey}' in the same call.")

                    kwargs[newkey] = kwargs[oldkey]
                    del kwargs[oldkey]

            return func(*args, **kwargs)

        return inner_wrapper

    return wrapper

# }}}


# {{{ math --------------------------------------------------------------------

def delta(x, y):
    if x == y:
        return 1
    else:
        return 0


def levi_civita(tup):
    """Compute an entry of the Levi-Civita tensor for the indices *tuple*."""
    if len(tup) == 2:
        i, j = tup
        return j-i
    if len(tup) == 3:
        i, j, k = tup
        return (j-i)*(k-i)*(k-j)/2
    else:
        raise NotImplementedError


def factorial(n):
    from operator import mul
    assert n == int(n)
    return reduce(mul, (i for i in range(1, n+1)), 1)


def perm(n, k):
    """Return P(n, k), the number of permutations of length k drawn from n
    choices.
    """
    result = 1
    assert k > 0
    while k:
        result *= n
        n -= 1
        k -= 1

    return result


def comb(n, k):
    """Return C(n, k), the number of combinations (subsets)
    of length k drawn from n choices.
    """
    return perm(n, k)//factorial(k)


def norm_1(iterable):
    return sum(abs(x) for x in iterable)


def norm_2(iterable):
    return sum(x**2 for x in iterable)**0.5


def norm_inf(iterable):
    return max(abs(x) for x in iterable)


def norm_p(iterable, p):
    return sum(i**p for i in iterable)**(1/p)


class Norm:
    def __init__(self, p):
        self.p = p

    def __call__(self, iterable):
        return sum(i**self.p for i in iterable)**(1/self.p)

# }}}


# {{{ data structures

# {{{ record

class RecordWithoutPickling:
    """An aggregate of named sub-variables. Assumes that each record sub-type
    will be individually derived from this class.
    """

    __slots__: List[str] = []

    def __init__(self, valuedict=None, exclude=None, **kwargs):
        assert self.__class__ is not Record

        if exclude is None:
            exclude = ["self"]

        try:
            fields = self.__class__.fields
        except AttributeError:
            self.__class__.fields = fields = set()

        if valuedict is not None:
            kwargs.update(valuedict)

        for key, value in kwargs.items():
            if key not in exclude:
                fields.add(key)
                setattr(self, key, value)

    def get_copy_kwargs(self, **kwargs):
        for f in self.__class__.fields:
            if f not in kwargs:
                try:
                    kwargs[f] = getattr(self, f)
                except AttributeError:
                    pass
        return kwargs

    def copy(self, **kwargs):
        return self.__class__(**self.get_copy_kwargs(**kwargs))

    def __repr__(self):
        return "{}({})".format(
                self.__class__.__name__,
                ", ".join("{}={!r}".format(fld, getattr(self, fld))
                    for fld in self.__class__.fields
                    if hasattr(self, fld)))

    def register_fields(self, new_fields):
        try:
            fields = self.__class__.fields
        except AttributeError:
            self.__class__.fields = fields = set()

        fields.update(new_fields)

    def __getattr__(self, name):
        # This method is implemented to avoid pylint 'no-member' errors for
        # attribute access.
        raise AttributeError(
                "'{}' object has no attribute '{}'".format(
                    self.__class__.__name__, name))


class Record(RecordWithoutPickling):
    __slots__: List[str] = []

    def __getstate__(self):
        return {
                key: getattr(self, key)
                for key in self.__class__.fields
                if hasattr(self, key)}

    def __setstate__(self, valuedict):
        try:
            fields = self.__class__.fields
        except AttributeError:
            self.__class__.fields = fields = set()

        for key, value in valuedict.items():
            fields.add(key)
            setattr(self, key, value)

    def __eq__(self, other):
        return (self.__class__ == other.__class__
                and self.__getstate__() == other.__getstate__())

    def __ne__(self, other):
        return not self.__eq__(other)


class ImmutableRecordWithoutPickling(RecordWithoutPickling):
    """Hashable record. Does not explicitly enforce immutability."""
    def __init__(self, *args, **kwargs):
        RecordWithoutPickling.__init__(self, *args, **kwargs)
        self._cached_hash = None

    def __hash__(self):
        if self._cached_hash is None:
            self._cached_hash = hash(
                (type(self),) + tuple(getattr(self, field)
                    for field in self.__class__.fields))

        return self._cached_hash


class ImmutableRecord(ImmutableRecordWithoutPickling, Record):
    pass

# }}}


class Reference:
    def __init__(self, value):
        self.value = value

    def get(self):
        from warnings import warn
        warn("Reference.get() is deprecated -- use ref.value instead")
        return self.value

    def set(self, value):
        self.value = value


class FakeList:
    def __init__(self, f, length):
        self._Length = length
        self._Function = f

    def __len__(self):
        return self._Length

    def __getitem__(self, index):
        try:
            return [self._Function(i)
                    for i in range(*index.indices(self._Length))]
        except AttributeError:
            return self._Function(index)


# {{{ dependent dictionary ----------------------------------------------------

class DependentDictionary:
    def __init__(self, f, start=None):
        if start is None:
            start = {}

        self._Function = f
        self._Dictionary = start.copy()

    def copy(self):
        return DependentDictionary(self._Function, self._Dictionary)

    def __contains__(self, key):
        try:
            self[key]  # pylint: disable=pointless-statement
            return True
        except KeyError:
            return False

    def __getitem__(self, key):
        try:
            return self._Dictionary[key]
        except KeyError:
            return self._Function(self._Dictionary, key)

    def __setitem__(self, key, value):
        self._Dictionary[key] = value

    def genuineKeys(self):  # noqa
        return list(self._Dictionary.keys())

    def iteritems(self):
        return self._Dictionary.items()

    def iterkeys(self):
        return self._Dictionary.keys()

    def itervalues(self):
        return self._Dictionary.values()

# }}}

# }}}


# {{{ assertive accessors

def one(iterable: Iterable[T]) -> T:
    """Return the first entry of *iterable*. Assert that *iterable* has only
    that one entry.
    """
    it = iter(iterable)
    try:
        v = next(it)
    except StopIteration:
        raise ValueError("empty iterable passed to 'one()'")

    def no_more():
        try:
            next(it)
            raise ValueError("iterable with more than one entry passed to 'one()'")
        except StopIteration:
            return True

    assert no_more()

    return v


def is_single_valued(
        iterable: Iterable[T],
        equality_pred: Callable[[T, T], bool] = operator.eq
        ) -> bool:
    it = iter(iterable)
    try:
        first_item = next(it)
    except StopIteration:
        raise ValueError("empty iterable passed to 'single_valued()'")

    for other_item in it:
        if not equality_pred(other_item, first_item):
            return False
    return True


all_equal = is_single_valued


def all_roughly_equal(iterable, threshold):
    return is_single_valued(iterable,
            equality_pred=lambda a, b: abs(a-b) < threshold)


def single_valued(
        iterable: Iterable[T],
        equality_pred: Callable[[T, T], bool] = operator.eq
        ) -> T:
    """Return the first entry of *iterable*; Assert that other entries
    are the same with the first entry of *iterable*.
    """
    it = iter(iterable)
    try:
        first_item = next(it)
    except StopIteration:
        raise ValueError("empty iterable passed to 'single_valued()'")

    def others_same():
        for other_item in it:
            if not equality_pred(other_item, first_item):
                return False
        return True
    assert others_same()

    return first_item

# }}}


# {{{ memoization / attribute storage

def memoize(*args: F, **kwargs: Any) -> F:
    """Stores previously computed function values in a cache.

    Two keyword-only arguments are supported:

    :arg use_kwargs: Allows the caller to use keyword arguments. Defaults to
        ``False``. Setting this to ``True`` has a non-negligible performance
        impact.
    :arg key: A function receiving the same arguments as the decorated function
        which computes and returns the cache key.
    """

    use_kw = bool(kwargs.pop("use_kwargs", False))

    default_key_func: Optional[Callable[..., Any]]

    if use_kw:
        def default_key_func(*inner_args, **inner_kwargs):  # noqa pylint:disable=function-redefined
            return inner_args, frozenset(inner_kwargs.items())
    else:
        default_key_func = None

    key_func = kwargs.pop("key", default_key_func)

    if kwargs:
        raise TypeError(
            "memoize received unexpected keyword arguments: %s"
            % ", ".join(list(kwargs.keys())))

    if key_func is not None:
        @my_decorator
        def _deco(func, *args, **kwargs):
            # by Michele Simionato
            # http://www.phyast.pitt.edu/~micheles/python/
            key = key_func(*args, **kwargs)
            try:
                return func._memoize_dic[key]  # pylint: disable=protected-access
            except AttributeError:
                # _memoize_dic doesn't exist yet.
                result = func(*args, **kwargs)
                func._memoize_dic = {key: result}  # pylint: disable=protected-access
                return result
            except KeyError:
                result = func(*args, **kwargs)
                func._memoize_dic[key] = result  # pylint: disable=protected-access
                return result
    else:
        @my_decorator
        def _deco(func, *args):
            # by Michele Simionato
            # http://www.phyast.pitt.edu/~micheles/python/
            try:
                return func._memoize_dic[args]  # pylint: disable=protected-access
            except AttributeError:
                # _memoize_dic doesn't exist yet.
                result = func(*args)
                func._memoize_dic = {args: result}  # pylint:disable=protected-access
                return result
            except KeyError:
                result = func(*args)
                func._memoize_dic[args] = result  # pylint: disable=protected-access
                return result

    if not args:
        return _deco
    if callable(args[0]) and len(args) == 1:
        return _deco(args[0])
    raise TypeError(
        "memoize received unexpected position arguments: %s" % args)


FunctionValueCache = memoize


class _HasKwargs:
    pass


def memoize_on_first_arg(function, cache_dict_name=None):
    """Like :func:`memoize_method`, but for functions that take the object
    in which do memoization information is stored as first argument.

    Supports cache deletion via ``function_name.clear_cache(self)``.
    """

    if cache_dict_name is None:
        cache_dict_name = intern("_memoize_dic_"
                + function.__module__ + function.__name__)

    def wrapper(obj, *args, **kwargs):
        if kwargs:
            key = (_HasKwargs, frozenset(kwargs.items())) + args
        else:
            key = args

        try:
            return getattr(obj, cache_dict_name)[key]
        except AttributeError:
            result = function(obj, *args, **kwargs)
            setattr(obj, cache_dict_name, {key: result})
            return result
        except KeyError:
            result = function(obj, *args, **kwargs)
            getattr(obj, cache_dict_name)[key] = result
            return result

    def clear_cache(obj):
        delattr(obj, cache_dict_name)

    from functools import update_wrapper
    new_wrapper = update_wrapper(wrapper, function)
    new_wrapper.clear_cache = clear_cache

    return new_wrapper


def memoize_method(method: F) -> F:
    """Supports cache deletion via ``method_name.clear_cache(self)``.
    """

    return memoize_on_first_arg(method, intern("_memoize_dic_"+method.__name__))


class keyed_memoize_on_first_arg:  # noqa: N801
    """Like :func:`memoize_method`, but for functions that take the object
    in which memoization information is stored as first argument.

    Supports cache deletion via ``function_name.clear_cache(self)``.

    :arg key: A function receiving the same arguments as the decorated function
        which computes and returns the cache key.

    .. versionadded :: 2020.3
    """

    def __init__(self, key, cache_dict_name=None):
        self.key = key
        self.cache_dict_name = cache_dict_name

    def _default_cache_dict_name(self, function):
        return intern("_memoize_dic_"
                + function.__module__ + function.__name__)

    def __call__(self, function):
        cache_dict_name = self.cache_dict_name
        key = self.key

        if cache_dict_name is None:
            cache_dict_name = self._default_cache_dict_name(function)

        def wrapper(obj, *args, **kwargs):
            cache_key = key(*args, **kwargs)

            try:
                return getattr(obj, cache_dict_name)[cache_key]
            except AttributeError:
                result = function(obj, *args, **kwargs)
                setattr(obj, cache_dict_name, {cache_key: result})
                return result
            except KeyError:
                result = function(obj, *args, **kwargs)
                getattr(obj, cache_dict_name)[cache_key] = result
                return result

        def clear_cache(obj):
            delattr(obj, cache_dict_name)

        from functools import update_wrapper
        new_wrapper = update_wrapper(wrapper, function)
        new_wrapper.clear_cache = clear_cache

        return new_wrapper


class keyed_memoize_method(keyed_memoize_on_first_arg):  # noqa: N801
    """Supports cache deletion via ``method_name.clear_cache(self)``.

    :arg key: A function receiving the same arguments as the decorated function
        which computes and returns the cache key.

    .. versionadded :: 2020.3
    """
    def _default_cache_dict_name(self, function):
        return intern("_memoize_dic_" + function.__name__)


def memoize_method_with_uncached(uncached_args=None, uncached_kwargs=None):
    """Supports cache deletion via ``method_name.clear_cache(self)``.

    :arg uncached_args: a list of argument numbers
        (0-based, not counting 'self' argument)
    """
    from warnings import warn
    warn("memoize_method_with_uncached is deprecated and will go away in 2022. "
            "Use memoize_method_with_key instead",
            DeprecationWarning,
            stacklevel=2)

    if uncached_args is None:
        uncached_args = []
    if uncached_kwargs is None:
        uncached_kwargs = set()

    # delete starting from the end
    uncached_args = sorted(uncached_args, reverse=True)
    uncached_kwargs = list(uncached_kwargs)

    def parametrized_decorator(method):
        cache_dict_name = intern("_memoize_dic_"+method.__name__)

        def wrapper(self, *args, **kwargs):
            cache_args = list(args)
            cache_kwargs = kwargs.copy()

            for i in uncached_args:
                if i < len(cache_args):
                    cache_args.pop(i)

            cache_args = tuple(cache_args)

            if kwargs:
                for name in uncached_kwargs:
                    cache_kwargs.pop(name, None)

                key = (
                        (_HasKwargs, frozenset(cache_kwargs.items()))
                        + cache_args)
            else:
                key = cache_args

            try:
                return getattr(self, cache_dict_name)[key]
            except AttributeError:
                result = method(self, *args, **kwargs)
                setattr(self, cache_dict_name, {key: result})
                return result
            except KeyError:
                result = method(self, *args, **kwargs)
                getattr(self, cache_dict_name)[key] = result
                return result

        def clear_cache(self):
            delattr(self, cache_dict_name)

        if sys.version_info >= (2, 5):
            from functools import update_wrapper
            new_wrapper = update_wrapper(wrapper, method)
            new_wrapper.clear_cache = clear_cache

        return new_wrapper

    return parametrized_decorator


def memoize_method_nested(inner):
    """Adds a cache to a function nested inside a method. The cache is attached
    to *memoize_cache_context* (if it exists) or *self* in the outer (method)
    namespace.

    Requires Python 2.5 or newer.
    """

    from warnings import warn
    warn("memoize_method_nested is deprecated and will go away in 2021. "
            "Use @memoize_in(self, 'identifier') instead", DeprecationWarning,
            stacklevel=2)

    cache_dict_name = intern("_memoize_inner_dic_%s_%s_%d"
            % (inner.__name__, inner.__code__.co_filename,
                inner.__code__.co_firstlineno))

    from inspect import currentframe
    outer_frame = currentframe().f_back
    cache_context = outer_frame.f_locals.get("memoize_cache_context")
    if cache_context is None:
        cache_context = outer_frame.f_locals.get("self")

    try:
        cache_dict = getattr(cache_context, cache_dict_name)
    except AttributeError:
        cache_dict = {}
        setattr(cache_context, cache_dict_name, cache_dict)

    @wraps(inner)
    def new_inner(*args):
        try:
            return cache_dict[args]
        except KeyError:
            result = inner(*args)
            cache_dict[args] = result
            return result

    return new_inner


class memoize_in:  # noqa
    """Adds a cache to a function nested inside a method. The cache is attached
    to *container*.

    .. versionchanged :: 2020.3

        *identifier* no longer needs to be a :class:`str`,
        but it needs to be hashable.
    """

    def __init__(self, container, identifier):
        try:
            memoize_in_dict = container._pytools_memoize_in_dict
        except AttributeError:
            memoize_in_dict = {}
            container._pytools_memoize_in_dict = memoize_in_dict

        self.cache_dict = memoize_in_dict.setdefault(identifier, {})

    def __call__(self, inner):
        @wraps(inner)
        def new_inner(*args):
            try:
                return self.cache_dict[args]
            except KeyError:
                result = inner(*args)
                self.cache_dict[args] = result
                return result

        return new_inner

# }}}


# {{{ syntactical sugar

class InfixOperator:
    """Pseudo-infix operators that allow syntax of the kind `op1 <<operator>> op2'.

    Following a recipe from
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122
    """
    def __init__(self, function):
        self.function = function

    def __rlshift__(self, other):
        return InfixOperator(lambda x: self.function(other, x))

    def __rshift__(self, other):
        return self.function(other)

    def call(self, a, b):
        return self.function(a, b)


def monkeypatch_method(cls):
    # from GvR, http://mail.python.org/pipermail/python-dev/2008-January/076194.html
    def decorator(func):
        setattr(cls, func.__name__, func)
        return func
    return decorator


def monkeypatch_class(_name, bases, namespace):
    # from GvR, http://mail.python.org/pipermail/python-dev/2008-January/076194.html

    assert len(bases) == 1, "Exactly one base class required"
    base = bases[0]
    for name, value in namespace.items():
        if name != "__metaclass__":
            setattr(base, name, value)
    return base

# }}}


# {{{ generic utilities

def add_tuples(t1, t2):
    return tuple([t1v + t2v for t1v, t2v in zip(t1, t2)])


def negate_tuple(t1):
    return tuple([-t1v for t1v in t1])


def shift(vec, dist):
    """Return a copy of C{vec} shifted by C{dist}.

    @postcondition: C{shift(a, i)[j] == a[(i+j) % len(a)]}
    """

    result = vec[:]

    N = len(vec)  # noqa
    dist = dist % N

    # modulo only returns positive distances!
    if dist > 0:
        result[dist:] = vec[:N-dist]
        result[:dist] = vec[N-dist:]

    return result


def len_iterable(iterable):
    return sum(1 for i in iterable)


def flatten(iterable):
    """For an iterable of sub-iterables, generate each member of each
    sub-iterable in turn, i.e. a flattened version of that super-iterable.

    Example: Turn [[a,b,c],[d,e,f]] into [a,b,c,d,e,f].
    """
    for sublist in iterable:
        yield from sublist


def general_sum(sequence):
    return reduce(operator.add, sequence)


def linear_combination(coefficients, vectors):
    result = coefficients[0] * vectors[0]
    for c, v in zip(coefficients[1:], vectors[1:]):
        result += c*v
    return result


def common_prefix(iterable, empty=None):
    it = iter(iterable)
    try:
        pfx = next(it)
    except StopIteration:
        return empty

    for v in it:
        for j, pfx_j in enumerate(pfx):
            if pfx_j != v[j]:
                pfx = pfx[:j]
                if j == 0:
                    return pfx
                break

    return pfx


def decorate(function, iterable):
    return [(x, function(x)) for x in iterable]


def partition(criterion, iterable):
    part_true = []
    part_false = []
    for i in iterable:
        if criterion(i):
            part_true.append(i)
        else:
            part_false.append(i)
    return part_true, part_false


def partition2(iterable):
    part_true = []
    part_false = []
    for pred, i in iterable:
        if pred:
            part_true.append(i)
        else:
            part_false.append(i)
    return part_true, part_false


def product(iterable: Iterable[Any]) -> Any:
    from operator import mul
    return reduce(mul, iterable, 1)


def reverse_dictionary(the_dict):
    result = {}
    for key, value in the_dict.items():
        if value in result:
            raise RuntimeError(
                    "non-reversible mapping, duplicate key '%s'" % value)
        result[value] = key
    return result


def set_sum(set_iterable):
    from operator import or_
    return reduce(or_, set_iterable, set())


def div_ceil(nr, dr):
    return -(-nr // dr)


def uniform_interval_splitting(n, granularity, max_intervals):
    """ Return *(interval_size, num_intervals)* such that::

        num_intervals * interval_size >= n

    and::

        (num_intervals - 1) * interval_size < n

    and *interval_size* is a multiple of *granularity*.
    """
    # ported from Thrust

    grains = div_ceil(n, granularity)

    # one grain per interval
    if grains <= max_intervals:
        return granularity, grains

    grains_per_interval = div_ceil(grains, max_intervals)
    interval_size = grains_per_interval * granularity
    num_intervals = div_ceil(n, interval_size)

    return interval_size, num_intervals


def find_max_where(predicate, prec=1e-5, initial_guess=1, fail_bound=1e38):
    """Find the largest value for which a predicate is true,
    along a half-line. 0 is assumed to be the lower bound."""

    # {{{ establish bracket

    mag = initial_guess

    if predicate(mag):
        mag *= 2
        while predicate(mag):
            mag *= 2

            if mag > fail_bound:
                raise RuntimeError("predicate appears to be true "
                        "everywhere, up to %g" % fail_bound)

        lower_true = mag/2
        upper_false = mag
    else:
        mag /= 2

        while not predicate(mag):
            mag /= 2

            if mag < prec:
                return mag

        lower_true = mag
        upper_false = mag*2

    # }}}

    # {{{ refine

    # Refine a bracket between *lower_true*, where the predicate is true,
    # and *upper_false*, where it is false, until *prec* is satisfied.

    assert predicate(lower_true)
    assert not predicate(upper_false)

    while abs(lower_true-upper_false) > prec:
        mid = (lower_true+upper_false)/2
        if predicate(mid):
            lower_true = mid
        else:
            upper_false = mid

    return lower_true

    # }}}

# }}}


# {{{ argmin, argmax

def argmin2(iterable, return_value=False):
    it = iter(iterable)
    try:
        current_argmin, current_min = next(it)
    except StopIteration:
        raise ValueError("argmin of empty iterable")

    for arg, item in it:
        if item < current_min:
            current_argmin = arg
            current_min = item

    if return_value:
        return current_argmin, current_min
    else:
        return current_argmin


def argmax2(iterable, return_value=False):
    it = iter(iterable)
    try:
        current_argmax, current_max = next(it)
    except StopIteration:
        raise ValueError("argmax of empty iterable")

    for arg, item in it:
        if item > current_max:
            current_argmax = arg
            current_max = item

    if return_value:
        return current_argmax, current_max
    else:
        return current_argmax


def argmin(iterable):
    return argmin2(enumerate(iterable))


def argmax(iterable):
    return argmax2(enumerate(iterable))

# }}}


# {{{ cartesian products etc.

def cartesian_product(*args):
    if len(args) == 1:
        for arg in args[0]:
            yield (arg,)
        return
    first = args[:-1]
    for prod in cartesian_product(*first):
        for i in args[-1]:
            yield prod + (i,)


def distinct_pairs(list1, list2):
    for i, xi in enumerate(list1):
        for j, yj in enumerate(list2):
            if i != j:
                yield (xi, yj)


def cartesian_product_sum(list1, list2):
    """This routine returns a list of sums of each element of
    list1 with each element of list2. Also works with lists.
    """
    for i in list1:
        for j in list2:
            yield i+j

# }}}


# {{{ elementary statistics

def average(iterable):
    """Return the average of the values in iterable.

    iterable may not be empty.
    """
    it = iterable.__iter__()

    try:
        s = next(it)
        count = 1
    except StopIteration:
        raise ValueError("empty average")

    for value in it:
        s = s + value
        count += 1

    return s/count


class VarianceAggregator:
    """Online variance calculator.
    See http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
    Adheres to pysqlite's aggregate interface.
    """
    def __init__(self, entire_pop):
        self.n = 0
        self.mean = 0
        self.m2 = 0

        self.entire_pop = entire_pop

    def step(self, x):
        self.n += 1
        delta_ = x - self.mean
        self.mean += delta_/self.n
        self.m2 += delta_*(x - self.mean)

    def finalize(self):
        if self.entire_pop:
            if self.n == 0:
                return None
            else:
                return self.m2/self.n
        else:
            if self.n <= 1:
                return None
            else:
                return self.m2/(self.n - 1)


def variance(iterable, entire_pop):
    v_comp = VarianceAggregator(entire_pop)

    for x in iterable:
        v_comp.step(x)

    return v_comp.finalize()


def std_deviation(iterable, finite_pop):
    from math import sqrt
    return sqrt(variance(iterable, finite_pop))

# }}}


# {{{ permutations, tuples, integer sequences

def wandering_element(length, wanderer=1, landscape=0):
    for i in range(length):
        yield i*(landscape,) + (wanderer,) + (length-1-i)*(landscape,)


def indices_in_shape(shape):
    from warnings import warn
    warn("indices_in_shape is deprecated. You should prefer numpy.ndindex.",
            DeprecationWarning, stacklevel=2)

    if isinstance(shape, int):
        shape = (shape,)

    if not shape:
        yield ()
    elif len(shape) == 1:
        for i in range(0, shape[0]):
            yield (i,)
    else:
        remainder = shape[1:]
        for i in range(0, shape[0]):
            for rest in indices_in_shape(remainder):
                yield (i,)+rest


def generate_nonnegative_integer_tuples_below(n, length=None, least=0):
    """n may be a sequence, in which case length must be None."""
    if length is None:
        if not n:
            yield ()
            return

        my_n = n[0]
        n = n[1:]
        next_length = None
    else:
        my_n = n

        assert length >= 0
        if length == 0:
            yield ()
            return

        next_length = length-1

    for i in range(least, my_n):
        my_part = (i,)
        for base in generate_nonnegative_integer_tuples_below(n, next_length, least):
            yield my_part + base


def generate_decreasing_nonnegative_tuples_summing_to(
        n, length, min_value=0, max_value=None):
    if length == 0:
        yield ()
    elif length == 1:
        if n <= max_value:
            #print "MX", n, max_value
            yield (n,)
        else:
            return
    else:
        if max_value is None or n < max_value:
            max_value = n

        for i in range(min_value, max_value+1):
            #print "SIG", sig, i
            for remainder in generate_decreasing_nonnegative_tuples_summing_to(
                    n-i, length-1, min_value, i):
                yield (i,) + remainder


def generate_nonnegative_integer_tuples_summing_to_at_most(n, length):
    """Enumerate all non-negative integer tuples summing to at most n,
    exhausting the search space by varying the first entry fastest,
    and the last entry the slowest.
    """
    assert length >= 0
    if length == 0:
        yield ()
    else:
        for i in range(n+1):
            for remainder in generate_nonnegative_integer_tuples_summing_to_at_most(
                    n-i, length-1):
                yield remainder + (i,)


def generate_all_nonnegative_integer_tuples(length, least=0):
    assert length >= 0
    current_max = least
    while True:
        for max_pos in range(length):
            for prebase in generate_nonnegative_integer_tuples_below(
                    current_max, max_pos, least):
                for postbase in generate_nonnegative_integer_tuples_below(
                        current_max+1, length-max_pos-1, least):
                    yield prebase + [current_max] + postbase
        current_max += 1


# backwards compatibility
generate_positive_integer_tuples_below = generate_nonnegative_integer_tuples_below
generate_all_positive_integer_tuples = generate_all_nonnegative_integer_tuples


def _pos_and_neg_adaptor(tuple_iter):
    for tup in tuple_iter:
        nonzero_indices = [i for i in range(len(tup)) if tup[i] != 0]
        for do_neg_tup in generate_nonnegative_integer_tuples_below(
                2, len(nonzero_indices)):
            this_result = list(tup)
            for index, do_neg in enumerate(do_neg_tup):
                if do_neg:
                    this_result[nonzero_indices[index]] *= -1
            yield tuple(this_result)


def generate_all_integer_tuples_below(n, length, least_abs=0):
    return _pos_and_neg_adaptor(generate_nonnegative_integer_tuples_below(
        n, length, least_abs))


def generate_all_integer_tuples(length, least_abs=0):
    return _pos_and_neg_adaptor(generate_all_nonnegative_integer_tuples(
        length, least_abs))


def generate_permutations(original):
    """Generate all permutations of the list *original*.

    Nicked from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252178
    """
    if len(original) <= 1:
        yield original
    else:
        for perm_ in generate_permutations(original[1:]):
            for i in range(len(perm_)+1):
                #nb str[0:1] works in both string and list contexts
                yield perm_[:i] + original[0:1] + perm_[i:]


def generate_unique_permutations(original):
    """Generate all unique permutations of the list *original*.
    """

    had_those = set()

    for perm_ in generate_permutations(original):
        if perm_ not in had_those:
            had_those.add(perm_)
            yield perm_


def enumerate_basic_directions(dimensions):
    coordinate_list = [[0], [1], [-1]]
    return reduce(cartesian_product_sum, [coordinate_list] * dimensions)[1:]

# }}}


# {{{ index mangling

def get_read_from_map_from_permutation(original, permuted):
    """With a permutation given by *original* and *permuted*,
    generate a list *rfm* of indices such that
    ``permuted[i] == original[rfm[i]]``.

    Requires that the permutation can be inferred from
    *original* and *permuted*.

    .. doctest ::

        >>> for p1 in generate_permutations(list(range(5))):
        ...     for p2 in generate_permutations(list(range(5))):
        ...         rfm = get_read_from_map_from_permutation(p1, p2)
        ...         p2a = [p1[rfm[i]] for i in range(len(p1))]
        ...         assert p2 == p2a
    """
    from warnings import warn
    warn("get_read_from_map_from_permutation is deprecated and will be "
            "removed in 2019", DeprecationWarning, stacklevel=2)

    assert len(original) == len(permuted)
    where_in_original = {
            original[i]: i for i in range(len(original))}
    assert len(where_in_original) == len(original)
    return tuple(where_in_original[pi] for pi in permuted)


def get_write_to_map_from_permutation(original, permuted):
    """With a permutation given by *original* and *permuted*,
    generate a list *wtm* of indices such that
    ``permuted[wtm[i]] == original[i]``.

    Requires that the permutation can be inferred from
    *original* and *permuted*.

    .. doctest ::

        >>> for p1 in generate_permutations(list(range(5))):
        ...     for p2 in generate_permutations(list(range(5))):
        ...         wtm = get_write_to_map_from_permutation(p1, p2)
        ...         p2a = [0] * len(p2)
        ...         for i, oi in enumerate(p1):
        ...             p2a[wtm[i]] = oi
        ...         assert p2 == p2a
    """
    from warnings import warn
    warn("get_write_to_map_from_permutation is deprecated and will be "
            "removed in 2019", DeprecationWarning, stacklevel=2)

    assert len(original) == len(permuted)

    where_in_permuted = {
            permuted[i]: i for i in range(len(permuted))}

    assert len(where_in_permuted) == len(permuted)
    return tuple(where_in_permuted[oi] for oi in original)

# }}}


# {{{ graph algorithms

from pytools.graph import a_star as a_star_moved
a_star = MovedFunctionDeprecationWrapper(a_star_moved)

# }}}


# {{{ formatting

# {{{ table formatting

class Table:
    """An ASCII table generator.

    :arg alignments: List of alignments of each column ('l', 'c', or 'r',
        for left, center, and right alignment, respectively). Columns which
        have no alignment specifier will use the last specified alignment. For
        example, with `alignments=['l', 'r']`, the third and all following
        columns will use 'r' alignment.

    .. automethod:: add_row
    .. automethod:: __str__
    .. automethod:: latex
    .. automethod:: github_markdown
    """

    def __init__(self, alignments=None):
        self.rows = []
        if alignments is not None:
            self.alignments = alignments
        else:
            self.alignments = ["l"]

    def add_row(self, row):
        self.rows.append([str(i) for i in row])

    def __str__(self):
        """
        Returns a string representation of the table.

        .. doctest ::

            >>> tbl = Table(alignments=['l', 'r', 'l'])
            >>> tbl.add_row([1, '|'])
            >>> tbl.add_row([10, '20||'])
            >>> print(tbl)
            1  |    |
            ---+------
            10 | 20||

        """

        columns = len(self.rows[0])
        col_widths = [max(len(row[i]) for row in self.rows)
                      for i in range(columns)]

        alignments = self.alignments
        # If not all alignments were specified, extend alignments with the
        # last alignment specified:
        alignments += self.alignments[-1] * (columns - len(self.alignments))

        lines = [" | ".join([
            cell.center(col_width) if align == "c"
            else cell.ljust(col_width) if align == "l"
            else cell.rjust(col_width)
            for cell, col_width, align in zip(row, col_widths, alignments)])
            for row in self.rows]
        lines[1:1] = ["+".join("-" * (col_width + 1 + (i > 0))
            for i, col_width in enumerate(col_widths))]

        return "\n".join(lines)

    def github_markdown(self):
        r"""Returns a string representation of the table formatted as
        `GitHub-Flavored Markdown.
        <https://docs.github.com/en/github/writing-on-github/organizing-information-with-tables>`__

        .. doctest ::

            >>> tbl = Table(alignments=['l', 'r', 'l'])
            >>> tbl.add_row([1, '|'])
            >>> tbl.add_row([10, '20||'])
            >>> print(tbl.github_markdown())
            1  |     \|
            :--|-------:
            10 | 20\|\|

        """  # noqa: W605
        # Pipe symbols ('|') must be replaced
        rows = [[w.replace("|", "\\|") for w in r] for r in self.rows]

        columns = len(rows[0])
        col_widths = [max(len(row[i]) for row in rows)
                      for i in range(columns)]

        alignments = self.alignments
        # If not all alignments were specified, extend alignments with the
        # last alignment specified:
        alignments += self.alignments[-1] * (columns - len(self.alignments))

        lines = [" | ".join([
            cell.center(col_width) if align == "c"
            else cell.ljust(col_width) if align == "l"
            else cell.rjust(col_width)
            for cell, col_width, align in zip(row, col_widths, alignments)])
            for row in rows]
        lines[1:1] = ["|".join(
            ":" + "-" * (col_width - 1 + (i > 0)) + ":" if align == "c"
            else ":" + "-" * (col_width + (i > 0)) if align == "l"
            else "-" * (col_width + (i > 0)) + ":"
            for i, (col_width, align) in enumerate(zip(col_widths, alignments)))]

        return "\n".join(lines)

    def csv(self, dialect="excel", csv_kwargs=None):
        """Returns a string containing a CSV representation of the table.

        :arg dialect: String passed to :func:`csv.writer`.
        :arg csv_kwargs: Dict of arguments passed to :func:`csv.writer`.

        .. doctest ::

            >>> tbl = Table()
            >>> tbl.add_row([1, ","])
            >>> tbl.add_row([10, 20])
            >>> print(tbl.csv())
            1,","
            10,20
        """

        import csv
        import io

        if csv_kwargs is None:
            csv_kwargs = {}

        # Default is "\r\n"
        if "lineterminator" not in csv_kwargs:
            csv_kwargs["lineterminator"] = "\n"

        output = io.StringIO()
        writer = csv.writer(output, dialect, **csv_kwargs)
        writer.writerows(self.rows)

        return output.getvalue().rstrip(csv_kwargs["lineterminator"])

    def latex(self, skip_lines=0, hline_after=None):
        if hline_after is None:
            hline_after = []
        lines = []
        for row_nr, row in list(enumerate(self.rows))[skip_lines:]:
            lines.append(" & ".join(row)+r" \\")
            if row_nr in hline_after:
                lines.append(r"\hline")

        return "\n".join(lines)

# }}}


# {{{ histogram formatting

def string_histogram(  # pylint: disable=too-many-arguments,too-many-locals
        iterable, min_value=None, max_value=None,
        bin_count=20, width=70, bin_starts=None, use_unicode=True):
    if bin_starts is None:
        if min_value is None or max_value is None:
            iterable = list(iterable)
            min_value = min(iterable)
            max_value = max(iterable)

        bin_width = (max_value - min_value)/bin_count
        bin_starts = [min_value+bin_width*i for i in range(bin_count)]

    bins = [0 for i in range(len(bin_starts))]

    from bisect import bisect
    for value in iterable:
        if max_value is not None and value > max_value or value < bin_starts[0]:
            from warnings import warn
            warn("string_histogram: out-of-bounds value ignored")
        else:
            bin_nr = bisect(bin_starts, value)-1
            try:
                bins[bin_nr] += 1
            except Exception:
                print(value, bin_nr, bin_starts)
                raise

    from math import floor, ceil
    if use_unicode:
        def format_bar(cnt):
            scaled = cnt*width/max_count
            full = int(floor(scaled))
            eighths = int(ceil((scaled-full)*8))
            if eighths:
                return full*chr(0x2588) + chr(0x2588+(8-eighths))
            else:
                return full*chr(0x2588)
    else:
        def format_bar(cnt):
            return int(ceil(cnt*width/max_count))*"#"

    max_count = max(bins)
    total_count = sum(bins)
    return "\n".join("%9g |%9d | %3.0f %% | %s" % (
        bin_start,
        bin_value,
        bin_value/total_count*100,
        format_bar(bin_value))
        for bin_start, bin_value in zip(bin_starts, bins))

# }}}


def word_wrap(text, width, wrap_using="\n"):
    # http://code.activestate.com/recipes/148061-one-liner-word-wrap-function/
    r"""
    A word-wrap function that preserves existing line breaks
    and most spaces in the text. Expects that existing line
    breaks are posix newlines (``\n``).
    """
    space_or_break = [" ", wrap_using]
    return reduce(lambda line, word: "%s%s%s" %
            (line,
                space_or_break[(len(line)-line.rfind("\n")-1
                    + len(word.split("\n", 1)[0])
                    >= width)],
                    word),
            text.split(" ")
            )

# }}}


# {{{ command line interfaces -------------------------------------------------

def _exec_arg(arg, execenv):
    import os
    if os.access(arg, os.F_OK):
        exec(compile(open(arg), arg, "exec"), execenv)
    else:
        exec(compile(arg, "<command line>", "exec"), execenv)


class CPyUserInterface:
    class Parameters(Record):
        pass

    def __init__(self, variables, constants=None, doc=None):
        if constants is None:
            constants = {}
        if doc is None:
            doc = {}
        self.variables = variables
        self.constants = constants
        self.doc = doc

    def show_usage(self, progname):
        print("usage: %s <FILE-OR-STATEMENTS>" % progname)
        print()
        print("FILE-OR-STATEMENTS may either be Python statements of the form")
        print("'variable1 = value1; variable2 = value2' or the name of a file")
        print("containing such statements. Any valid Python code may be used")
        print("on the command line or in a command file. If new variables are")
        print("used, they must start with 'user_' or just '_'.")
        print()
        print("The following variables are recognized:")
        for v in sorted(self.variables):
            print("  {} = {}".format(v, self.variables[v]))
            if v in self.doc:
                print("    %s" % self.doc[v])

        print()
        print("The following constants are supplied:")
        for c in sorted(self.constants):
            print("  {} = {}".format(c, self.constants[c]))
            if c in self.doc:
                print("    %s" % self.doc[c])

    def gather(self, argv=None):
        if argv is None:
            argv = sys.argv

        if len(argv) == 1 or (
                ("-h" in argv)
                or ("help" in argv)
                or ("-help" in argv)
                or ("--help" in argv)):
            self.show_usage(argv[0])
            sys.exit(2)

        execenv = self.variables.copy()
        execenv.update(self.constants)

        for arg in argv[1:]:
            _exec_arg(arg, execenv)

        # check if the user set invalid keys
        for added_key in (
                set(execenv.keys())
                - set(self.variables.keys())
                - set(self.constants.keys())):
            if not (added_key.startswith("user_") or added_key.startswith("_")):
                raise ValueError(
                        "invalid setup key: '%s' "
                        "(user variables must start with 'user_' or '_')"
                        % added_key)

        result = self.Parameters({key: execenv[key] for key in self.variables})
        self.validate(result)
        return result

    def validate(self, setup):
        pass

# }}}


# {{{ debugging

class StderrToStdout:
    def __enter__(self):
        # pylint: disable=attribute-defined-outside-init
        self.stderr_backup = sys.stderr
        sys.stderr = sys.stdout

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stderr = self.stderr_backup
        del self.stderr_backup


def typedump(val, max_seq=5, special_handlers=None):
    if special_handlers is None:
        special_handlers = {}

    try:
        hdlr = special_handlers[type(val)]
    except KeyError:
        pass
    else:
        return hdlr(val)

    try:
        len(val)
    except TypeError:
        return type(val).__name__
    else:
        if isinstance(val, dict):
            return "{%s}" % (
                    ", ".join(
                        "{!r}: {}".format(str(k), typedump(v))
                        for k, v in val.items()))

        try:
            if len(val) > max_seq:
                return "{}({},...)".format(
                        type(val).__name__,
                        ",".join(typedump(x, max_seq, special_handlers)
                            for x in val[:max_seq]))
            else:
                return "{}({})".format(
                        type(val).__name__,
                        ",".join(typedump(x, max_seq, special_handlers)
                            for x in val))
        except TypeError:
            return val.__class__.__name__


def invoke_editor(s, filename="edit.txt", descr="the file"):
    from tempfile import mkdtemp
    tempdir = mkdtemp()

    from os.path import join
    full_name = join(tempdir, filename)

    outf = open(full_name, "w")
    outf.write(str(s))
    outf.close()

    import os
    if "EDITOR" in os.environ:
        from subprocess import Popen
        p = Popen([os.environ["EDITOR"], full_name])
        os.waitpid(p.pid, 0)
    else:
        print("(Set the EDITOR environment variable to be "
                "dropped directly into an editor next time.)")
        input("Edit %s at %s now, then hit [Enter]:"
                % (descr, full_name))

    inf = open(full_name)
    result = inf.read()
    inf.close()

    return result

# }}}


# {{{ progress bars

class ProgressBar:  # pylint: disable=too-many-instance-attributes
    """
    .. automethod:: draw
    .. automethod:: progress
    .. automethod:: set_progress
    .. automethod:: finished
    .. automethod:: __enter__
    .. automethod:: __exit__
    """
    def __init__(self, descr, total, initial=0, length=40):
        import time
        self.description = descr
        self.total = total
        self.done = initial
        self.length = length
        self.last_squares = -1
        self.start_time = time.time()
        self.last_update_time = self.start_time

        self.speed_meas_start_time = self.start_time
        self.speed_meas_start_done = initial

        self.time_per_step = None

    def draw(self):
        import time

        now = time.time()
        squares = int(self.done/self.total*self.length)
        if squares != self.last_squares or now-self.last_update_time > 0.5:
            if (self.done != self.speed_meas_start_done
                    and now-self.speed_meas_start_time > 3):
                new_time_per_step = (now-self.speed_meas_start_time) \
                        / (self.done-self.speed_meas_start_done)
                if self.time_per_step is not None:
                    self.time_per_step = (new_time_per_step + self.time_per_step)/2
                else:
                    self.time_per_step = new_time_per_step

                self.speed_meas_start_time = now
                self.speed_meas_start_done = self.done

            if self.time_per_step is not None:
                eta_str = "%7.1fs " % max(
                        0, (self.total-self.done) * self.time_per_step)
            else:
                eta_str = "?"

            sys.stderr.write("{:<20} [{}] ETA {}\r".format(
                self.description,
                squares*"#"+(self.length-squares)*" ",
                eta_str))

            self.last_squares = squares
            self.last_update_time = now

    def progress(self, steps=1):
        self.set_progress(self.done + steps)

    def set_progress(self, done):
        self.done = done
        self.draw()

    def finished(self):
        self.set_progress(self.total)
        sys.stderr.write("\n")

    def __enter__(self):
        self.draw()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.finished()

# }}}


# {{{ file system related

def assert_not_a_file(name):
    import os
    if os.access(name, os.F_OK):
        raise OSError("file `%s' already exists" % name)


def add_python_path_relative_to_script(rel_path):
    from os.path import dirname, join, abspath

    script_name = sys.argv[0]
    rel_script_dir = dirname(script_name)

    sys.path.append(abspath(join(rel_script_dir, rel_path)))

# }}}


# {{{ numpy dtype mangling

def common_dtype(dtypes, default=None):
    dtypes = list(dtypes)
    if dtypes:
        return argmax2((dtype, dtype.num) for dtype in dtypes)
    else:
        if default is not None:
            return default
        else:
            raise ValueError(
                    "cannot find common dtype of empty dtype list")


def to_uncomplex_dtype(dtype):
    import numpy
    if dtype == numpy.complex64:
        return numpy.float32
    elif dtype == numpy.complex128:
        return numpy.float64
    if dtype == numpy.float32:
        return numpy.float32
    elif dtype == numpy.float64:
        return numpy.float64
    else:
        raise TypeError("unrecgonized dtype '%s'" % dtype)


def match_precision(dtype, dtype_to_match):
    import numpy

    tgt_is_double = dtype_to_match in [
            numpy.float64, numpy.complex128]

    dtype_is_complex = dtype.kind == "c"
    if dtype_is_complex:
        if tgt_is_double:
            return numpy.dtype(numpy.complex128)
        else:
            return numpy.dtype(numpy.complex64)
    else:
        if tgt_is_double:
            return numpy.dtype(numpy.float64)
        else:
            return numpy.dtype(numpy.float32)

# }}}


# {{{ unique name generation

def generate_unique_names(prefix):
    yield prefix

    try_num = 0
    while True:
        yield "%s_%d" % (prefix, try_num)
        try_num += 1


def generate_numbered_unique_names(
        prefix: str, num: Optional[int] = None) -> Iterable[Tuple[int, str]]:
    if num is None:
        yield (0, prefix)
        num = 0

    while True:
        name = "%s_%d" % (prefix, num)
        num += 1
        yield (num, name)


generate_unique_possibilities = MovedFunctionDeprecationWrapper(
        generate_unique_names)


class UniqueNameGenerator:
    """
    .. automethod:: is_name_conflicting
    .. automethod:: add_name
    .. automethod:: add_names
    .. automethod:: __call__
    """
    def __init__(self,
            existing_names: Optional[Set[str]] = None,
            forced_prefix: str = ""):
        if existing_names is None:
            existing_names = set()

        self.existing_names = existing_names.copy()
        self.forced_prefix = forced_prefix
        self.prefix_to_counter: Dict[str, int] = {}

    def is_name_conflicting(self, name: str) -> bool:
        return name in self.existing_names

    def _name_added(self, name: str) -> None:
        """Callback to alert subclasses when a name has been added.

        .. note::

            This will not get called for the names in the *existing_names*
            argument to :meth:`__init__`.
        """
        pass

    def add_name(self, name: str) -> None:
        if self.is_name_conflicting(name):
            raise ValueError("name '%s' conflicts with existing names")
        if not name.startswith(self.forced_prefix):
            raise ValueError("name '%s' does not start with required prefix")

        self.existing_names.add(name)
        self._name_added(name)

    def add_names(self, names: Iterable[str]) -> None:
        for name in names:
            self.add_name(name)

    def __call__(self, based_on: str = "id") -> str:
        based_on = self.forced_prefix + based_on

        counter = self.prefix_to_counter.get(based_on, None)

        for counter, var_name in generate_numbered_unique_names(based_on, counter):
            if not self.is_name_conflicting(var_name):
                break

        self.prefix_to_counter[based_on] = counter

        var_name = intern(var_name)  # pylint: disable=undefined-loop-variable

        self.existing_names.add(var_name)
        self._name_added(var_name)
        return var_name

# }}}


# {{{ recursion limit

class MinRecursionLimit:
    def __init__(self, min_rec_limit):
        self.min_rec_limit = min_rec_limit

    def __enter__(self):
        # pylint: disable=attribute-defined-outside-init

        self.prev_recursion_limit = sys.getrecursionlimit()
        new_limit = max(self.prev_recursion_limit, self.min_rec_limit)
        sys.setrecursionlimit(new_limit)

    def __exit__(self, exc_type, exc_val, exc_tb):
        # Deep recursion can produce deeply nested data structures
        # (or long chains of to-be gc'd generators) that cannot be
        # undergo garbage collection with a lower recursion limit.
        #
        # As a result, it doesn't seem possible to lower the recursion limit
        # again after it has been raised without causing reliability issues.
        #
        # See https://gitlab.tiker.net/inducer/sumpy/issues/31 for
        # context.

        pass

# }}}


# {{{ download from web if not present

def download_from_web_if_not_present(url, local_name=None):
    """
    .. versionadded:: 2017.5
    """

    from os.path import basename, exists
    if local_name is None:
        local_name = basename(url)

    if not exists(local_name):
        from pytools.version import VERSION_TEXT
        from urllib.request import Request, urlopen
        req = Request(url, headers={
            "User-Agent": f"pytools/{VERSION_TEXT}"
            })

        with urlopen(req) as inf:
            contents = inf.read()

            with open(local_name, "wb") as outf:
                outf.write(contents)

# }}}


# {{{ find git revisions

def find_git_revision(tree_root):  # pylint: disable=too-many-locals
    # Keep this routine self-contained so that it can be copy-pasted into
    # setup.py.

    from os.path import join, exists, abspath
    tree_root = abspath(tree_root)

    if not exists(join(tree_root, ".git")):
        return None

    # construct minimal environment
    # stolen from
    # https://github.com/numpy/numpy/blob/055ce3e90b50b5f9ef8cf1b8641c42e391f10735/setup.py#L70-L92
    import os
    env = {}
    for k in ["SYSTEMROOT", "PATH", "HOME"]:
        v = os.environ.get(k)
        if v is not None:
            env[k] = v
    # LANGUAGE is used on win32
    env["LANGUAGE"] = "C"
    env["LANG"] = "C"
    env["LC_ALL"] = "C"

    from subprocess import Popen, PIPE, STDOUT
    p = Popen(["git", "rev-parse", "HEAD"], shell=False,
              stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True,
              cwd=tree_root, env=env)
    (git_rev, _) = p.communicate()

    git_rev = git_rev.decode()

    git_rev = git_rev.rstrip()

    retcode = p.returncode
    assert retcode is not None
    if retcode != 0:
        from warnings import warn
        warn("unable to find git revision")
        return None

    return git_rev


def find_module_git_revision(module_file, n_levels_up):
    from os.path import dirname, join
    tree_root = join(*([dirname(module_file)] + [".." * n_levels_up]))

    return find_git_revision(tree_root)

# }}}


# {{{ create a reshaped view of a numpy array

def reshaped_view(a, newshape):
    """ Create a new view object with shape ``newshape`` without copying the data of
    ``a``. This function is different from ``numpy.reshape`` by raising an
    exception when data copy is necessary.

    :arg a: a :class:`numpy.ndarray` object.
    :arg newshape: an ``int`` object or a tuple of ``int`` objects.

    .. versionadded:: 2018.4
    """

    newview = a.view()
    newview.shape = newshape
    return newview

# }}}


# {{{ process timer

SUPPORTS_PROCESS_TIME = (sys.version_info >= (3, 3))


class ProcessTimer:
    """Measures elapsed wall time and process time.

    .. automethod:: __enter__
    .. automethod:: __exit__
    .. automethod:: done

    Timing data attributes:

    .. attribute:: wall_elapsed
    .. attribute:: process_elapsed

        Only available in Python 3.3+.

    .. versionadded:: 2018.5
    """

    def __init__(self):
        import time
        if SUPPORTS_PROCESS_TIME:
            self.perf_counter_start = time.perf_counter()
            self.process_time_start = time.process_time()

        else:
            import timeit
            self.time_start = timeit.default_timer()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.done()

    def done(self):
        # pylint: disable=attribute-defined-outside-init

        import time
        if SUPPORTS_PROCESS_TIME:
            self.wall_elapsed = time.perf_counter() - self.perf_counter_start
            self.process_elapsed = time.process_time() - self.process_time_start

        else:
            import timeit
            self.wall_elapsed = timeit.default_timer() - self.time_start
            self.process_elapsed = None

# }}}


# {{{ log utilities

class ProcessLogger:  # pylint: disable=too-many-instance-attributes
    """Logs the completion time of a (presumably) lengthy process to :mod:`logging`.
    Only uses a high log level if the process took perceptible time.

    .. automethod:: __init__
    .. automethod:: done
    .. automethod:: __enter__
    .. automethod:: __exit__
    """

    default_noisy_level = logging.INFO

    def __init__(  # pylint: disable=too-many-arguments
            self, logger, description,
            silent_level=None, noisy_level=None, long_threshold_seconds=None):
        self.logger = logger
        self.description = description
        self.silent_level = silent_level or logging.DEBUG
        self.noisy_level = noisy_level or self.default_noisy_level
        self.long_threshold_seconds = (
                # 0 is a valid value that should override the default
                0.3 if long_threshold_seconds is None else long_threshold_seconds)

        self.logger.log(self.silent_level, "%s: start", self.description)
        self.is_done = False

        import threading
        self.late_start_log_thread = threading.Thread(target=self._log_start_if_long)

        # Do not delay interpreter exit if thread not finished.
        self.late_start_log_thread.daemon = True

        # https://github.com/firedrakeproject/firedrake/issues/1422
        # Starting a thread may irrecoverably break various environments,
        # e.g. MPI.
        #
        # Since the late-start logging is an optional 'quality-of-life'
        # feature for interactive use, do not do it unless there is (weak)
        # evidence of interactive use.
        import sys
        if sys.stdin is None:
            # Can happen, e.g., if pudb is controlling the console.
            use_late_start_logging = False
        else:
            use_late_start_logging = sys.stdin.isatty()

        import os
        if os.environ.get("PYTOOLS_LOG_NO_THREADS", ""):
            use_late_start_logging = False

        if use_late_start_logging:
            try:
                self.late_start_log_thread.start()
            except RuntimeError:
                # https://github.com/firedrakeproject/firedrake/issues/1422
                #
                # Starting a thread may fail in various environments, e.g. MPI.
                # Since the late-start logging is an optional 'quality-of-life'
                # feature for interactive use, tolerate failures of it without
                # warning.
                pass

        self.timer = ProcessTimer()

    def _log_start_if_long(self):
        from time import sleep

        sleep_duration = 10*self.long_threshold_seconds
        sleep(sleep_duration)

        if not self.is_done:
            self.logger.log(
                    self.noisy_level, "%s: started %.gs ago",
                    self.description,
                    sleep_duration)

    def done(  # pylint: disable=keyword-arg-before-vararg
            self, extra_msg=None, *extra_fmt_args):
        self.timer.done()
        self.is_done = True

        wall_elapsed = self.timer.wall_elapsed
        process_elapsed = self.timer.process_elapsed

        completion_level = (
                self.noisy_level
                if wall_elapsed > self.long_threshold_seconds
                else self.silent_level)

        if process_elapsed is not None:
            msg = "%s: completed (%.2fs wall, %.1fx CPU)"
            fmt_args = [self.description, wall_elapsed, process_elapsed/wall_elapsed]
        else:
            msg = "%s: completed (%f.2s wall)"
            fmt_args = [self.description, wall_elapsed]

        if extra_msg:
            msg += ": " + extra_msg
            fmt_args.extend(extra_fmt_args)

        self.logger.log(completion_level, msg, *fmt_args)

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.done()


class DebugProcessLogger(ProcessLogger):
    default_noisy_level = logging.DEBUG


class log_process:  # noqa: N801
    """A decorator that uses :class:`ProcessLogger` to log data about calls
    to the wrapped function.
    """

    def __init__(self, logger, description=None):
        self.logger = logger
        self.description = description

    def __call__(self, wrapped):
        def wrapper(*args, **kwargs):
            with ProcessLogger(
                    self.logger,
                    self.description or wrapped.__name__):
                return wrapped(*args, **kwargs)

        from functools import update_wrapper
        new_wrapper = update_wrapper(wrapper, wrapped)

        return new_wrapper

# }}}


# {{{ sorting in natural order

def natorder(item):
    """Return a key for natural order string comparison.

    See :func:`natsorted`.

    .. versionadded:: 2020.1
    """
    import re
    result = []
    for (int_val, string_val) in re.findall(r"(\d+)|(\D+)", item):
        if int_val:
            result.append(int(int_val))
            # Tie-breaker in case of leading zeros in *int_val*.  Longer values
            # compare smaller to preserve order of numbers in decimal notation,
            # e.g., "1.001" < "1.01"
            # (cf. https://github.com/sourcefrog/natsort)
            result.append(-len(int_val))
        else:
            result.append(string_val)
    return result


def natsorted(iterable, key=None, reverse=False):
    """Sort using natural order [1]_, as opposed to lexicographic order.

    Example::

        >>> sorted(["_10", "_1", "_9"]) == ["_1", "_10", "_9"]
        True
        >>> natsorted(["_10", "_1", "_9"]) == ["_1", "_9", "_10"]
        True

    :arg iterable: an iterable to be sorted. It must only have strings, unless
        *key* is specified.
    :arg key: if provided, a key function that returns strings for ordering
        using natural order.
    :arg reverse: if *True*, sorts in descending order.

    :returns: a sorted list

    .. [1] https://en.wikipedia.org/wiki/Natural_sort_order

    .. versionadded:: 2020.1
    """
    if key is None:
        key = lambda x: x
    return sorted(iterable, key=lambda y: natorder(key(y)), reverse=reverse)

# }}}


def _test():
    import doctest
    doctest.testmod()


if __name__ == "__main__":
    _test()

# vim: foldmethod=marker