mapFolding 0.5.1__py3-none-any.whl → 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mapFolding/__init__.py +6 -101
- mapFolding/basecamp.py +12 -10
- mapFolding/beDRY.py +96 -316
- mapFolding/filesystem.py +87 -0
- mapFolding/noHomeYet.py +20 -0
- mapFolding/oeis.py +39 -36
- mapFolding/reference/flattened.py +377 -0
- mapFolding/reference/hunterNumba.py +132 -0
- mapFolding/reference/irvineJavaPort.py +120 -0
- mapFolding/reference/jax.py +208 -0
- mapFolding/reference/lunnan.py +153 -0
- mapFolding/reference/lunnanNumpy.py +123 -0
- mapFolding/reference/lunnanWhile.py +121 -0
- mapFolding/reference/rotatedEntryPoint.py +240 -0
- mapFolding/reference/total_countPlus1vsPlusN.py +211 -0
- mapFolding/someAssemblyRequired/Z0Z_workbench.py +34 -0
- mapFolding/someAssemblyRequired/__init__.py +16 -0
- mapFolding/someAssemblyRequired/getLLVMforNoReason.py +21 -0
- mapFolding/someAssemblyRequired/ingredientsNumba.py +100 -0
- mapFolding/someAssemblyRequired/synthesizeCountingFunctions.py +7 -0
- mapFolding/someAssemblyRequired/synthesizeDataConverters.py +135 -0
- mapFolding/someAssemblyRequired/synthesizeNumba.py +91 -0
- mapFolding/someAssemblyRequired/synthesizeNumbaJob.py +417 -0
- mapFolding/someAssemblyRequired/synthesizeNumbaModules.py +91 -0
- mapFolding/someAssemblyRequired/transformationTools.py +425 -0
- mapFolding/someAssemblyRequired/whatWillBe.py +311 -0
- mapFolding/syntheticModules/__init__.py +0 -0
- mapFolding/syntheticModules/dataNamespaceFlattened.py +30 -0
- mapFolding/syntheticModules/numbaCount.py +90 -0
- mapFolding/syntheticModules/numbaCountExample.py +158 -0
- mapFolding/syntheticModules/numbaCountSequential.py +110 -0
- mapFolding/syntheticModules/numbaCount_doTheNeedful.py +13 -0
- mapFolding/syntheticModules/numba_doTheNeedful.py +12 -0
- mapFolding/syntheticModules/numba_doTheNeedfulExample.py +13 -0
- mapFolding/theDao.py +203 -227
- mapFolding/theSSOT.py +254 -123
- {mapFolding-0.5.1.dist-info → mapfolding-0.7.0.dist-info}/METADATA +10 -8
- mapfolding-0.7.0.dist-info/RECORD +50 -0
- {mapFolding-0.5.1.dist-info → mapfolding-0.7.0.dist-info}/WHEEL +1 -1
- {mapFolding-0.5.1.dist-info → mapfolding-0.7.0.dist-info}/top_level.txt +1 -0
- tests/__init__.py +0 -0
- tests/conftest.py +278 -0
- tests/test_computations.py +49 -0
- tests/test_filesystem.py +52 -0
- tests/test_oeis.py +128 -0
- tests/test_other.py +84 -0
- tests/test_tasks.py +50 -0
- mapFolding/theSSOTdatatypes.py +0 -156
- mapFolding-0.5.1.dist-info/RECORD +0 -14
- {mapFolding-0.5.1.dist-info → mapfolding-0.7.0.dist-info}/LICENSE +0 -0
- {mapFolding-0.5.1.dist-info → mapfolding-0.7.0.dist-info}/entry_points.txt +0 -0
mapFolding/filesystem.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Filesystem functions for mapFolding package."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
def saveFoldsTotal(pathFilename: str | os.PathLike[str], foldsTotal: int) -> None:
|
|
6
|
+
"""
|
|
7
|
+
Save foldsTotal with multiple fallback mechanisms.
|
|
8
|
+
|
|
9
|
+
Parameters:
|
|
10
|
+
pathFilename: Target save location
|
|
11
|
+
foldsTotal: Critical computed value to save
|
|
12
|
+
"""
|
|
13
|
+
try:
|
|
14
|
+
pathFilenameFoldsTotal = Path(pathFilename)
|
|
15
|
+
pathFilenameFoldsTotal.parent.mkdir(parents=True, exist_ok=True)
|
|
16
|
+
pathFilenameFoldsTotal.write_text(str(foldsTotal))
|
|
17
|
+
except Exception as ERRORmessage:
|
|
18
|
+
try:
|
|
19
|
+
print(f"\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n\n{foldsTotal=}\n\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n")
|
|
20
|
+
print(ERRORmessage)
|
|
21
|
+
print(f"\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n\n{foldsTotal=}\n\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n")
|
|
22
|
+
randomnessPlanB = (int(str(foldsTotal).strip()[-1]) + 1) * ['YO_']
|
|
23
|
+
filenameInfixUnique = ''.join(randomnessPlanB)
|
|
24
|
+
pathFilenamePlanB = os.path.join(os.getcwd(), 'foldsTotal' + filenameInfixUnique + '.txt')
|
|
25
|
+
writeStreamFallback = open(pathFilenamePlanB, 'w')
|
|
26
|
+
writeStreamFallback.write(str(foldsTotal))
|
|
27
|
+
writeStreamFallback.close()
|
|
28
|
+
print(str(pathFilenamePlanB))
|
|
29
|
+
except Exception:
|
|
30
|
+
print(foldsTotal)
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
def getFilenameFoldsTotal(mapShape: tuple[int, ...]) -> str:
|
|
34
|
+
"""Imagine your computer has been counting folds for 9 days, and when it tries to save your newly discovered value,
|
|
35
|
+
the filename is invalid. I bet you think this function is more important after that thought experiment.
|
|
36
|
+
|
|
37
|
+
Make a standardized filename for the computed value `foldsTotal`.
|
|
38
|
+
|
|
39
|
+
The filename takes into account
|
|
40
|
+
- the dimensions of the map, aka `mapShape`, aka `listDimensions`
|
|
41
|
+
- no spaces in the filename
|
|
42
|
+
- safe filesystem characters
|
|
43
|
+
- unique extension
|
|
44
|
+
- Python-safe strings:
|
|
45
|
+
- no starting with a number
|
|
46
|
+
- no reserved words
|
|
47
|
+
- no dashes or other special characters
|
|
48
|
+
- uh, I can't remember, but I found some other frustrating limitations
|
|
49
|
+
- if 'p' is still the first character of the filename, I picked that because it was the original identifier for the map shape in Lunnan's code
|
|
50
|
+
|
|
51
|
+
Parameters:
|
|
52
|
+
mapShape: A sequence of integers representing the dimensions of the map.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
filenameFoldsTotal: A filename string in format 'pMxN.foldsTotal' where M,N are sorted dimensions
|
|
56
|
+
"""
|
|
57
|
+
return 'p' + 'x'.join(str(dimension) for dimension in sorted(mapShape)) + '.foldsTotal'
|
|
58
|
+
|
|
59
|
+
def getPathFilenameFoldsTotal(mapShape: tuple[int, ...], pathLikeWriteFoldsTotal: str | os.PathLike[str] | None = None) -> Path:
|
|
60
|
+
"""Get a standardized path and filename for the computed value `foldsTotal`.
|
|
61
|
+
|
|
62
|
+
If you provide a directory, the function will append a standardized filename. If you provide a filename
|
|
63
|
+
or a relative path and filename, the function will prepend the default path.
|
|
64
|
+
|
|
65
|
+
Parameters:
|
|
66
|
+
mapShape: List of dimensions for the map folding problem.
|
|
67
|
+
pathLikeWriteFoldsTotal (pathJobRootDEFAULT): Path, filename, or relative path and filename. If None, uses default path.
|
|
68
|
+
Defaults to None.
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
pathFilenameFoldsTotal: Absolute path and filename.
|
|
72
|
+
"""
|
|
73
|
+
from mapFolding.theSSOT import getPathJobRootDEFAULT
|
|
74
|
+
|
|
75
|
+
if pathLikeWriteFoldsTotal is None:
|
|
76
|
+
pathFilenameFoldsTotal = getPathJobRootDEFAULT() / getFilenameFoldsTotal(mapShape)
|
|
77
|
+
else:
|
|
78
|
+
pathLikeSherpa = Path(pathLikeWriteFoldsTotal)
|
|
79
|
+
if pathLikeSherpa.is_dir():
|
|
80
|
+
pathFilenameFoldsTotal = pathLikeSherpa / getFilenameFoldsTotal(mapShape)
|
|
81
|
+
elif pathLikeSherpa.is_file() and pathLikeSherpa.is_absolute():
|
|
82
|
+
pathFilenameFoldsTotal = pathLikeSherpa
|
|
83
|
+
else:
|
|
84
|
+
pathFilenameFoldsTotal = getPathJobRootDEFAULT() / pathLikeSherpa
|
|
85
|
+
|
|
86
|
+
pathFilenameFoldsTotal.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
return pathFilenameFoldsTotal
|
mapFolding/noHomeYet.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from functools import cache
|
|
2
|
+
from mapFolding.oeis import settingsOEIS
|
|
3
|
+
|
|
4
|
+
@cache
|
|
5
|
+
def makeDictionaryFoldsTotalKnown() -> dict[tuple[int, ...], int]:
|
|
6
|
+
"""Returns a dictionary mapping dimension tuples to their known folding totals."""
|
|
7
|
+
dictionaryMapDimensionsToFoldsTotalKnown: dict[tuple[int, ...], int] = {}
|
|
8
|
+
|
|
9
|
+
for settings in settingsOEIS.values():
|
|
10
|
+
sequence = settings['valuesKnown']
|
|
11
|
+
|
|
12
|
+
for n, foldingsTotal in sequence.items():
|
|
13
|
+
mapShape = settings['getMapShape'](n)
|
|
14
|
+
mapShape = sorted(mapShape)
|
|
15
|
+
dictionaryMapDimensionsToFoldsTotalKnown[tuple(mapShape)] = foldingsTotal
|
|
16
|
+
return dictionaryMapDimensionsToFoldsTotalKnown
|
|
17
|
+
|
|
18
|
+
def getFoldsTotalKnown(mapShape: tuple[int, ...]) -> int:
|
|
19
|
+
lookupFoldsTotal = makeDictionaryFoldsTotalKnown()
|
|
20
|
+
return lookupFoldsTotal.get(tuple(mapShape), -1)
|
mapFolding/oeis.py
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
"""Everything implementing the The Online Encyclopedia of Integer Sequences (OEIS); _only_ things that implement _only_ the OEIS."""
|
|
2
2
|
from collections.abc import Callable
|
|
3
3
|
from datetime import datetime, timedelta
|
|
4
|
-
from mapFolding import
|
|
4
|
+
from mapFolding.theSSOT import thePathPackage
|
|
5
|
+
from pathlib import Path
|
|
5
6
|
from typing import Any, Final, TYPE_CHECKING
|
|
6
7
|
import argparse
|
|
7
8
|
import pathlib
|
|
8
|
-
from pathlib import Path
|
|
9
9
|
import random
|
|
10
10
|
import sys
|
|
11
11
|
import time
|
|
@@ -23,11 +23,11 @@ cacheDays = 7
|
|
|
23
23
|
"""
|
|
24
24
|
Section: make `settingsOEIS`"""
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
pathCache: Path = thePathPackage / ".cache"
|
|
27
27
|
|
|
28
28
|
class SettingsOEIS(TypedDict):
|
|
29
29
|
description: str
|
|
30
|
-
getMapShape: Callable[[int],
|
|
30
|
+
getMapShape: Callable[[int], tuple[int, ...]]
|
|
31
31
|
offset: int
|
|
32
32
|
valuesBenchmark: list[int]
|
|
33
33
|
valuesKnown: dict[int, int]
|
|
@@ -35,33 +35,39 @@ class SettingsOEIS(TypedDict):
|
|
|
35
35
|
valuesTestValidation: list[int]
|
|
36
36
|
valueUnknown: int
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
class SettingsOEIShardcodedValues(TypedDict):
|
|
39
|
+
getMapShape: Callable[[int], tuple[int, ...]]
|
|
40
|
+
valuesBenchmark: list[int]
|
|
41
|
+
valuesTestParallelization: list[int]
|
|
42
|
+
valuesTestValidation: list[int]
|
|
43
|
+
|
|
44
|
+
settingsOEIShardcodedValues: dict[str, SettingsOEIShardcodedValues] = {
|
|
39
45
|
'A001415': {
|
|
40
|
-
'getMapShape': lambda n:
|
|
46
|
+
'getMapShape': lambda n: (2, n) if n >= 2 else (n, 2),
|
|
41
47
|
'valuesBenchmark': [14],
|
|
42
48
|
'valuesTestParallelization': [*range(3, 7)],
|
|
43
49
|
'valuesTestValidation': [random.randint(2, 9)],
|
|
44
50
|
},
|
|
45
51
|
'A001416': {
|
|
46
|
-
'getMapShape': lambda n:
|
|
52
|
+
'getMapShape': lambda n: (3, n) if n >= 3 else (n, 3),
|
|
47
53
|
'valuesBenchmark': [9],
|
|
48
54
|
'valuesTestParallelization': [*range(3, 5)],
|
|
49
55
|
'valuesTestValidation': [random.randint(2, 6)],
|
|
50
56
|
},
|
|
51
57
|
'A001417': {
|
|
52
|
-
'getMapShape': lambda n:
|
|
58
|
+
'getMapShape': lambda n: tuple(2 for _dimension in range(n)),
|
|
53
59
|
'valuesBenchmark': [6],
|
|
54
60
|
'valuesTestParallelization': [*range(2, 4)],
|
|
55
61
|
'valuesTestValidation': [random.randint(2, 4)],
|
|
56
62
|
},
|
|
57
63
|
'A195646': {
|
|
58
|
-
'getMapShape': lambda n:
|
|
64
|
+
'getMapShape': lambda n: tuple(3 for _dimension in range(n)),
|
|
59
65
|
'valuesBenchmark': [3],
|
|
60
66
|
'valuesTestParallelization': [*range(2, 3)],
|
|
61
67
|
'valuesTestValidation': [2],
|
|
62
68
|
},
|
|
63
69
|
'A001418': {
|
|
64
|
-
'getMapShape': lambda n:
|
|
70
|
+
'getMapShape': lambda n: (n, n),
|
|
65
71
|
'valuesBenchmark': [5],
|
|
66
72
|
'valuesTestParallelization': [*range(2, 4)],
|
|
67
73
|
'valuesTestValidation': [random.randint(2, 4)],
|
|
@@ -180,7 +186,7 @@ def getOEISidValues(oeisID: str) -> dict[int, int]:
|
|
|
180
186
|
IOError: If there is an error reading from or writing to the local cache.
|
|
181
187
|
"""
|
|
182
188
|
|
|
183
|
-
pathFilenameCache: Path =
|
|
189
|
+
pathFilenameCache: Path = pathCache / getFilenameOEISbFile(oeisID)
|
|
184
190
|
url: str = f"https://oeis.org/{oeisID}/{getFilenameOEISbFile(oeisID)}"
|
|
185
191
|
|
|
186
192
|
oeisInformation: None | str = getOEISofficial(pathFilenameCache, url)
|
|
@@ -191,7 +197,7 @@ def getOEISidValues(oeisID: str) -> dict[int, int]:
|
|
|
191
197
|
|
|
192
198
|
def getOEISidInformation(oeisID: str) -> tuple[str, int]:
|
|
193
199
|
oeisID = validateOEISid(oeisID)
|
|
194
|
-
pathFilenameCache: Path =
|
|
200
|
+
pathFilenameCache: Path = pathCache / f"{oeisID}.txt"
|
|
195
201
|
url: str = f"https://oeis.org/search?q=id:{oeisID}&fmt=text"
|
|
196
202
|
|
|
197
203
|
oeisInformation: None | str = getOEISofficial(pathFilenameCache, url)
|
|
@@ -199,26 +205,23 @@ def getOEISidInformation(oeisID: str) -> tuple[str, int]:
|
|
|
199
205
|
if not oeisInformation:
|
|
200
206
|
return "Not found", -1
|
|
201
207
|
|
|
202
|
-
|
|
208
|
+
listDescriptionDeconstructed: list[str] = []
|
|
203
209
|
offset = None
|
|
204
|
-
for
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
offset_str: str = parts[2].split(',')[0]
|
|
214
|
-
offset = int(offset_str)
|
|
215
|
-
if not description_parts:
|
|
210
|
+
for ImaStr in oeisInformation.splitlines():
|
|
211
|
+
ImaStr = ImaStr.strip() + "I am writing code to string parse machine readable data because in 2025, people can't even spell enteroperableity."
|
|
212
|
+
secretCode, title, secretData =ImaStr.split(maxsplit=2)
|
|
213
|
+
if secretCode == '%N' and title == oeisID:
|
|
214
|
+
listDescriptionDeconstructed.append(secretData)
|
|
215
|
+
if secretCode == '%O' and title == oeisID:
|
|
216
|
+
offsetAsStr: str = secretData.split(',')[0]
|
|
217
|
+
offset = int(offsetAsStr)
|
|
218
|
+
if not listDescriptionDeconstructed:
|
|
216
219
|
warnings.warn(f"No description found for {oeisID}")
|
|
217
|
-
|
|
220
|
+
listDescriptionDeconstructed.append("No description found")
|
|
218
221
|
if offset is None:
|
|
219
222
|
warnings.warn(f"No offset found for {oeisID}")
|
|
220
223
|
offset = -1
|
|
221
|
-
description: str = ' '.join(
|
|
224
|
+
description: str = ' '.join(listDescriptionDeconstructed)
|
|
222
225
|
return description, offset
|
|
223
226
|
|
|
224
227
|
def makeSettingsOEIS() -> dict[str, SettingsOEIS]:
|
|
@@ -290,16 +293,16 @@ def oeisIDfor_n(oeisID: str, n: int | Any) -> int:
|
|
|
290
293
|
if not isinstance(n, int) or n < 0:
|
|
291
294
|
raise ValueError("`n` must be non-negative integer.")
|
|
292
295
|
|
|
293
|
-
|
|
296
|
+
mapShape: tuple[int, ...] = settingsOEIS[oeisID]['getMapShape'](n)
|
|
294
297
|
|
|
295
|
-
if n <= 1 or len(
|
|
298
|
+
if n <= 1 or len(mapShape) < 2:
|
|
296
299
|
offset: int = settingsOEIS[oeisID]['offset']
|
|
297
300
|
if n < offset:
|
|
298
301
|
raise ArithmeticError(f"OEIS sequence {oeisID} is not defined at n={n}.")
|
|
299
302
|
foldsTotal: int = settingsOEIS[oeisID]['valuesKnown'][n]
|
|
300
303
|
return foldsTotal
|
|
301
|
-
|
|
302
|
-
return countFolds(
|
|
304
|
+
from mapFolding.basecamp import countFolds
|
|
305
|
+
return countFolds(mapShape)
|
|
303
306
|
|
|
304
307
|
def OEIS_for_n() -> None:
|
|
305
308
|
"""Command-line interface for oeisIDfor_n."""
|
|
@@ -326,13 +329,13 @@ def OEIS_for_n() -> None:
|
|
|
326
329
|
|
|
327
330
|
def clearOEIScache() -> None:
|
|
328
331
|
"""Delete all cached OEIS sequence files."""
|
|
329
|
-
if not
|
|
330
|
-
print(f"Cache directory, {
|
|
332
|
+
if not pathCache.exists():
|
|
333
|
+
print(f"Cache directory, {pathCache}, not found - nothing to clear.")
|
|
331
334
|
return
|
|
332
335
|
for oeisID in settingsOEIS:
|
|
333
|
-
(
|
|
334
|
-
(
|
|
335
|
-
print(f"Cache cleared from {
|
|
336
|
+
( pathCache / f"{oeisID}.txt" ).unlink(missing_ok=True)
|
|
337
|
+
( pathCache / getFilenameOEISbFile(oeisID) ).unlink(missing_ok=True)
|
|
338
|
+
print(f"Cache cleared from {pathCache}")
|
|
336
339
|
|
|
337
340
|
def getOEISids() -> None:
|
|
338
341
|
"""Print all available OEIS sequence IDs that are directly implemented."""
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
"""The algorithm flattened into semantic sections.
|
|
2
|
+
This version is not maintained, so you may see differences from the current version."""
|
|
3
|
+
from numpy import integer
|
|
4
|
+
from numpy.typing import NDArray
|
|
5
|
+
from typing import List, Any, Final, Optional, Union, Sequence, Tuple, Type, TypedDict
|
|
6
|
+
import enum
|
|
7
|
+
import numpy
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
def countFolds(listDimensions: Sequence[int], computationDivisions = None, CPUlimit: Optional[Union[int, float, bool]] = None):
|
|
11
|
+
def doWhile():
|
|
12
|
+
|
|
13
|
+
while activeLeafGreaterThan0Condition():
|
|
14
|
+
|
|
15
|
+
if activeLeafIsTheFirstLeafCondition() or leafBelowSentinelIs1Condition():
|
|
16
|
+
|
|
17
|
+
if activeLeafGreaterThanLeavesTotalCondition():
|
|
18
|
+
foldsSubTotalsIncrement()
|
|
19
|
+
|
|
20
|
+
else:
|
|
21
|
+
|
|
22
|
+
findGapsInitializeVariables()
|
|
23
|
+
while loopingTheDimensions():
|
|
24
|
+
|
|
25
|
+
if dimensionsUnconstrainedCondition():
|
|
26
|
+
dimensionsUnconstrainedIncrement()
|
|
27
|
+
|
|
28
|
+
else:
|
|
29
|
+
|
|
30
|
+
leafConnecteeInitialization()
|
|
31
|
+
while loopingLeavesConnectedToActiveLeaf():
|
|
32
|
+
if thereAreComputationDivisionsYouMightSkip():
|
|
33
|
+
countGaps()
|
|
34
|
+
leafConnecteeUpdate()
|
|
35
|
+
|
|
36
|
+
dimension1ndexIncrement()
|
|
37
|
+
|
|
38
|
+
if allDimensionsAreUnconstrained():
|
|
39
|
+
insertUnconstrainedLeaf()
|
|
40
|
+
|
|
41
|
+
indexMiniGapInitialization()
|
|
42
|
+
while loopingToActiveGapCeiling():
|
|
43
|
+
filterCommonGaps()
|
|
44
|
+
indexMiniGapIncrement()
|
|
45
|
+
|
|
46
|
+
while backtrackCondition():
|
|
47
|
+
backtrack()
|
|
48
|
+
|
|
49
|
+
if placeLeafCondition():
|
|
50
|
+
placeLeaf()
|
|
51
|
+
|
|
52
|
+
def activeGapIncrement():
|
|
53
|
+
my[indexMy.gap1ndex] += 1
|
|
54
|
+
|
|
55
|
+
def activeLeafGreaterThan0Condition():
|
|
56
|
+
return my[indexMy.leaf1ndex] > 0
|
|
57
|
+
|
|
58
|
+
def activeLeafGreaterThanLeavesTotalCondition():
|
|
59
|
+
return my[indexMy.leaf1ndex] > the[indexThe.leavesTotal]
|
|
60
|
+
|
|
61
|
+
def activeLeafIsTheFirstLeafCondition():
|
|
62
|
+
return my[indexMy.leaf1ndex] <= 1
|
|
63
|
+
|
|
64
|
+
def activeLeafNotEqualToTaskDivisionsCondition():
|
|
65
|
+
return my[indexMy.leaf1ndex] != the[indexThe.taskDivisions]
|
|
66
|
+
|
|
67
|
+
def allDimensionsAreUnconstrained():
|
|
68
|
+
return my[indexMy.dimensionsUnconstrained] == the[indexThe.dimensionsTotal]
|
|
69
|
+
|
|
70
|
+
def backtrack():
|
|
71
|
+
my[indexMy.leaf1ndex] -= 1
|
|
72
|
+
track[indexTrack.leafBelow, track[indexTrack.leafAbove, my[indexMy.leaf1ndex]]] = track[indexTrack.leafBelow, my[indexMy.leaf1ndex]]
|
|
73
|
+
track[indexTrack.leafAbove, track[indexTrack.leafBelow, my[indexMy.leaf1ndex]]] = track[indexTrack.leafAbove, my[indexMy.leaf1ndex]]
|
|
74
|
+
|
|
75
|
+
def backtrackCondition():
|
|
76
|
+
return my[indexMy.leaf1ndex] > 0 and my[indexMy.gap1ndex] == track[indexTrack.gapRangeStart, my[indexMy.leaf1ndex] - 1]
|
|
77
|
+
|
|
78
|
+
def computationDivisionsCondition():
|
|
79
|
+
return the[indexThe.taskDivisions] == int(False)
|
|
80
|
+
|
|
81
|
+
def countGaps():
|
|
82
|
+
gapsWhere[my[indexMy.gap1ndexCeiling]] = my[indexMy.leafConnectee]
|
|
83
|
+
if track[indexTrack.countDimensionsGapped, my[indexMy.leafConnectee]] == 0:
|
|
84
|
+
gap1ndexCeilingIncrement()
|
|
85
|
+
track[indexTrack.countDimensionsGapped, my[indexMy.leafConnectee]] += 1
|
|
86
|
+
|
|
87
|
+
def dimension1ndexIncrement():
|
|
88
|
+
my[indexMy.dimension1ndex] += 1
|
|
89
|
+
|
|
90
|
+
def dimensionsUnconstrainedCondition():
|
|
91
|
+
return connectionGraph[my[indexMy.dimension1ndex], my[indexMy.leaf1ndex], my[indexMy.leaf1ndex]] == my[indexMy.leaf1ndex]
|
|
92
|
+
|
|
93
|
+
def dimensionsUnconstrainedIncrement():
|
|
94
|
+
my[indexMy.dimensionsUnconstrained] += 1
|
|
95
|
+
|
|
96
|
+
def filterCommonGaps():
|
|
97
|
+
gapsWhere[my[indexMy.gap1ndex]] = gapsWhere[my[indexMy.indexMiniGap]]
|
|
98
|
+
if track[indexTrack.countDimensionsGapped, gapsWhere[my[indexMy.indexMiniGap]]] == the[indexThe.dimensionsTotal] - my[indexMy.dimensionsUnconstrained]:
|
|
99
|
+
activeGapIncrement()
|
|
100
|
+
track[indexTrack.countDimensionsGapped, gapsWhere[my[indexMy.indexMiniGap]]] = 0
|
|
101
|
+
|
|
102
|
+
def findGapsInitializeVariables():
|
|
103
|
+
my[indexMy.dimensionsUnconstrained] = 0
|
|
104
|
+
my[indexMy.gap1ndexCeiling] = track[indexTrack.gapRangeStart, my[indexMy.leaf1ndex] - 1]
|
|
105
|
+
my[indexMy.dimension1ndex] = 1
|
|
106
|
+
|
|
107
|
+
def foldsSubTotalsIncrement():
|
|
108
|
+
foldsSubTotals[my[indexMy.taskIndex]] += the[indexThe.leavesTotal]
|
|
109
|
+
|
|
110
|
+
def gap1ndexCeilingIncrement():
|
|
111
|
+
my[indexMy.gap1ndexCeiling] += 1
|
|
112
|
+
|
|
113
|
+
def indexMiniGapIncrement():
|
|
114
|
+
my[indexMy.indexMiniGap] += 1
|
|
115
|
+
|
|
116
|
+
def indexMiniGapInitialization():
|
|
117
|
+
my[indexMy.indexMiniGap] = my[indexMy.gap1ndex]
|
|
118
|
+
|
|
119
|
+
def insertUnconstrainedLeaf():
|
|
120
|
+
my[indexMy.indexLeaf] = 0
|
|
121
|
+
while my[indexMy.indexLeaf] < my[indexMy.leaf1ndex]:
|
|
122
|
+
gapsWhere[my[indexMy.gap1ndexCeiling]] = my[indexMy.indexLeaf]
|
|
123
|
+
my[indexMy.gap1ndexCeiling] += 1
|
|
124
|
+
my[indexMy.indexLeaf] += 1
|
|
125
|
+
|
|
126
|
+
def leafBelowSentinelIs1Condition():
|
|
127
|
+
return track[indexTrack.leafBelow, 0] == 1
|
|
128
|
+
|
|
129
|
+
def leafConnecteeInitialization():
|
|
130
|
+
my[indexMy.leafConnectee] = connectionGraph[my[indexMy.dimension1ndex], my[indexMy.leaf1ndex], my[indexMy.leaf1ndex]]
|
|
131
|
+
|
|
132
|
+
def leafConnecteeUpdate():
|
|
133
|
+
my[indexMy.leafConnectee] = connectionGraph[my[indexMy.dimension1ndex], my[indexMy.leaf1ndex], track[indexTrack.leafBelow, my[indexMy.leafConnectee]]]
|
|
134
|
+
|
|
135
|
+
def loopingLeavesConnectedToActiveLeaf():
|
|
136
|
+
return my[indexMy.leafConnectee] != my[indexMy.leaf1ndex]
|
|
137
|
+
|
|
138
|
+
def loopingTheDimensions():
|
|
139
|
+
return my[indexMy.dimension1ndex] <= the[indexThe.dimensionsTotal]
|
|
140
|
+
|
|
141
|
+
def loopingToActiveGapCeiling():
|
|
142
|
+
return my[indexMy.indexMiniGap] < my[indexMy.gap1ndexCeiling]
|
|
143
|
+
|
|
144
|
+
def placeLeaf():
|
|
145
|
+
my[indexMy.gap1ndex] -= 1
|
|
146
|
+
track[indexTrack.leafAbove, my[indexMy.leaf1ndex]] = gapsWhere[my[indexMy.gap1ndex]]
|
|
147
|
+
track[indexTrack.leafBelow, my[indexMy.leaf1ndex]] = track[indexTrack.leafBelow, track[indexTrack.leafAbove, my[indexMy.leaf1ndex]]]
|
|
148
|
+
track[indexTrack.leafBelow, track[indexTrack.leafAbove, my[indexMy.leaf1ndex]]] = my[indexMy.leaf1ndex]
|
|
149
|
+
track[indexTrack.leafAbove, track[indexTrack.leafBelow, my[indexMy.leaf1ndex]]] = my[indexMy.leaf1ndex]
|
|
150
|
+
track[indexTrack.gapRangeStart, my[indexMy.leaf1ndex]] = my[indexMy.gap1ndex]
|
|
151
|
+
my[indexMy.leaf1ndex] += 1
|
|
152
|
+
|
|
153
|
+
def placeLeafCondition():
|
|
154
|
+
return my[indexMy.leaf1ndex] > 0
|
|
155
|
+
|
|
156
|
+
def taskIndexCondition():
|
|
157
|
+
return my[indexMy.leafConnectee] % the[indexThe.taskDivisions] == my[indexMy.taskIndex]
|
|
158
|
+
|
|
159
|
+
def thereAreComputationDivisionsYouMightSkip():
|
|
160
|
+
if computationDivisionsCondition():
|
|
161
|
+
return True
|
|
162
|
+
if activeLeafNotEqualToTaskDivisionsCondition():
|
|
163
|
+
return True
|
|
164
|
+
if taskIndexCondition():
|
|
165
|
+
return True
|
|
166
|
+
return False
|
|
167
|
+
|
|
168
|
+
stateUniversal = outfitFoldings(listDimensions, computationDivisions=computationDivisions, CPUlimit=CPUlimit)
|
|
169
|
+
connectionGraph: Final[numpy.ndarray] = stateUniversal['connectionGraph']
|
|
170
|
+
foldsSubTotals = stateUniversal['foldsSubTotals']
|
|
171
|
+
gapsWhere = stateUniversal['gapsWhere']
|
|
172
|
+
my = stateUniversal['my']
|
|
173
|
+
the: Final[numpy.ndarray] = stateUniversal['the']
|
|
174
|
+
track = stateUniversal['track']
|
|
175
|
+
|
|
176
|
+
if the[indexThe.taskDivisions] == int(False):
|
|
177
|
+
doWhile()
|
|
178
|
+
else:
|
|
179
|
+
stateUniversal['my'] = my.copy()
|
|
180
|
+
stateUniversal['gapsWhere'] = gapsWhere.copy()
|
|
181
|
+
stateUniversal['track'] = track.copy()
|
|
182
|
+
for indexSherpa in range(the[indexThe.taskDivisions]):
|
|
183
|
+
my = stateUniversal['my'].copy()
|
|
184
|
+
my[indexMy.taskIndex] = indexSherpa
|
|
185
|
+
gapsWhere = stateUniversal['gapsWhere'].copy()
|
|
186
|
+
track = stateUniversal['track'].copy()
|
|
187
|
+
doWhile()
|
|
188
|
+
|
|
189
|
+
return numpy.sum(foldsSubTotals).item()
|
|
190
|
+
|
|
191
|
+
@enum.verify(enum.CONTINUOUS, enum.UNIQUE) if sys.version_info >= (3, 11) else lambda x: x
|
|
192
|
+
class EnumIndices(enum.IntEnum):
|
|
193
|
+
"""Base class for index enums."""
|
|
194
|
+
@staticmethod
|
|
195
|
+
def _generate_next_value_(name, start, count, last_values):
|
|
196
|
+
"""0-indexed."""
|
|
197
|
+
return count
|
|
198
|
+
|
|
199
|
+
def __index__(self) -> int:
|
|
200
|
+
"""Adapt enum to the ultra-rare event of indexing a NumPy 'ndarray', which is not the
|
|
201
|
+
same as `array.array`. See NumPy.org; I think it will be very popular someday."""
|
|
202
|
+
return self
|
|
203
|
+
|
|
204
|
+
class indexMy(EnumIndices):
|
|
205
|
+
"""Indices for dynamic values."""
|
|
206
|
+
dimension1ndex = enum.auto()
|
|
207
|
+
dimensionsUnconstrained = enum.auto()
|
|
208
|
+
gap1ndex = enum.auto()
|
|
209
|
+
gap1ndexCeiling = enum.auto()
|
|
210
|
+
indexLeaf = enum.auto()
|
|
211
|
+
indexMiniGap = enum.auto()
|
|
212
|
+
leaf1ndex = enum.auto()
|
|
213
|
+
leafConnectee = enum.auto()
|
|
214
|
+
taskIndex = enum.auto()
|
|
215
|
+
|
|
216
|
+
class indexThe(EnumIndices):
|
|
217
|
+
"""Indices for static values."""
|
|
218
|
+
dimensionsTotal = enum.auto()
|
|
219
|
+
leavesTotal = enum.auto()
|
|
220
|
+
taskDivisions = enum.auto()
|
|
221
|
+
|
|
222
|
+
class indexTrack(EnumIndices):
|
|
223
|
+
"""Indices for state tracking array."""
|
|
224
|
+
leafAbove = enum.auto()
|
|
225
|
+
leafBelow = enum.auto()
|
|
226
|
+
countDimensionsGapped = enum.auto()
|
|
227
|
+
gapRangeStart = enum.auto()
|
|
228
|
+
|
|
229
|
+
class computationState(TypedDict):
|
|
230
|
+
connectionGraph: NDArray[integer[Any]]
|
|
231
|
+
foldsSubTotals: NDArray[integer[Any]]
|
|
232
|
+
mapShape: Tuple[int, ...]
|
|
233
|
+
my: NDArray[integer[Any]]
|
|
234
|
+
gapsWhere: NDArray[integer[Any]]
|
|
235
|
+
the: NDArray[integer[Any]]
|
|
236
|
+
track: NDArray[integer[Any]]
|
|
237
|
+
|
|
238
|
+
dtypeLarge = numpy.int64
|
|
239
|
+
dtypeMedium = dtypeLarge
|
|
240
|
+
|
|
241
|
+
def getLeavesTotal(listDimensions: Sequence[int]) -> int:
|
|
242
|
+
"""
|
|
243
|
+
How many leaves are in the map.
|
|
244
|
+
|
|
245
|
+
Parameters:
|
|
246
|
+
listDimensions: A list of integers representing dimensions.
|
|
247
|
+
|
|
248
|
+
Returns:
|
|
249
|
+
productDimensions: The product of all positive integer dimensions.
|
|
250
|
+
"""
|
|
251
|
+
listNonNegative = parseDimensions(listDimensions, 'listDimensions')
|
|
252
|
+
listPositive = [dimension for dimension in listNonNegative if dimension > 0]
|
|
253
|
+
|
|
254
|
+
if not listPositive:
|
|
255
|
+
return 0
|
|
256
|
+
else:
|
|
257
|
+
productDimensions = 1
|
|
258
|
+
for dimension in listPositive:
|
|
259
|
+
if dimension > sys.maxsize // productDimensions:
|
|
260
|
+
raise OverflowError(f"I received {dimension=} in {listDimensions=}, but the product of the dimensions exceeds the maximum size of an integer on this system.")
|
|
261
|
+
productDimensions *= dimension
|
|
262
|
+
|
|
263
|
+
return productDimensions
|
|
264
|
+
|
|
265
|
+
def getTaskDivisions(computationDivisions: Optional[Union[int, str]], concurrencyLimit: int, CPUlimit: Optional[Union[bool, float, int]], listDimensions: Sequence[int]):
|
|
266
|
+
if not computationDivisions:
|
|
267
|
+
return 0
|
|
268
|
+
else:
|
|
269
|
+
leavesTotal = getLeavesTotal(listDimensions)
|
|
270
|
+
taskDivisions = 0
|
|
271
|
+
if isinstance(computationDivisions, int):
|
|
272
|
+
taskDivisions = computationDivisions
|
|
273
|
+
elif isinstance(computationDivisions, str):
|
|
274
|
+
computationDivisions = computationDivisions.lower()
|
|
275
|
+
if computationDivisions == "maximum":
|
|
276
|
+
taskDivisions = leavesTotal
|
|
277
|
+
elif computationDivisions == "cpu":
|
|
278
|
+
taskDivisions = min(concurrencyLimit, leavesTotal)
|
|
279
|
+
else:
|
|
280
|
+
raise ValueError("Not my problem.")
|
|
281
|
+
|
|
282
|
+
if taskDivisions > leavesTotal:
|
|
283
|
+
raise ValueError("What are you doing?")
|
|
284
|
+
|
|
285
|
+
return taskDivisions
|
|
286
|
+
|
|
287
|
+
def makeConnectionGraph(listDimensions: Sequence[int], **keywordArguments: Optional[Type]) -> NDArray[integer[Any]]:
|
|
288
|
+
datatype = keywordArguments.get('datatype', dtypeMedium)
|
|
289
|
+
mapShape = validateListDimensions(listDimensions)
|
|
290
|
+
leavesTotal = getLeavesTotal(mapShape)
|
|
291
|
+
arrayDimensions = numpy.array(mapShape, dtype=datatype)
|
|
292
|
+
dimensionsTotal = len(arrayDimensions)
|
|
293
|
+
|
|
294
|
+
cumulativeProduct = numpy.multiply.accumulate([1] + mapShape, dtype=datatype)
|
|
295
|
+
coordinateSystem = numpy.zeros((dimensionsTotal + 1, leavesTotal + 1), dtype=datatype)
|
|
296
|
+
for dimension1ndex in range(1, dimensionsTotal + 1):
|
|
297
|
+
for leaf1ndex in range(1, leavesTotal + 1):
|
|
298
|
+
coordinateSystem[dimension1ndex, leaf1ndex] = ( ((leaf1ndex - 1) // cumulativeProduct[dimension1ndex - 1]) % arrayDimensions[dimension1ndex - 1] + 1 )
|
|
299
|
+
|
|
300
|
+
connectionGraph = numpy.zeros((dimensionsTotal + 1, leavesTotal + 1, leavesTotal + 1), dtype=datatype)
|
|
301
|
+
for dimension1ndex in range(1, dimensionsTotal + 1):
|
|
302
|
+
for activeLeaf1ndex in range(1, leavesTotal + 1):
|
|
303
|
+
for connectee1ndex in range(1, activeLeaf1ndex + 1):
|
|
304
|
+
isFirstCoord = coordinateSystem[dimension1ndex, connectee1ndex] == 1
|
|
305
|
+
isLastCoord = coordinateSystem[dimension1ndex, connectee1ndex] == arrayDimensions[dimension1ndex - 1]
|
|
306
|
+
exceedsActive = connectee1ndex + cumulativeProduct[dimension1ndex - 1] > activeLeaf1ndex
|
|
307
|
+
isEvenParity = (coordinateSystem[dimension1ndex, activeLeaf1ndex] & 1) == (coordinateSystem[dimension1ndex, connectee1ndex] & 1)
|
|
308
|
+
|
|
309
|
+
if (isEvenParity and isFirstCoord) or (not isEvenParity and (isLastCoord or exceedsActive)):
|
|
310
|
+
connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex
|
|
311
|
+
elif isEvenParity and not isFirstCoord:
|
|
312
|
+
connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex - cumulativeProduct[dimension1ndex - 1]
|
|
313
|
+
elif not isEvenParity and not (isLastCoord or exceedsActive):
|
|
314
|
+
connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex + cumulativeProduct[dimension1ndex - 1]
|
|
315
|
+
else:
|
|
316
|
+
connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex
|
|
317
|
+
return connectionGraph
|
|
318
|
+
|
|
319
|
+
def makeDataContainer(shape, datatype: Optional[Type] = None):
|
|
320
|
+
if datatype is None:
|
|
321
|
+
datatype = dtypeMedium
|
|
322
|
+
return numpy.zeros(shape, dtype=datatype)
|
|
323
|
+
|
|
324
|
+
def outfitFoldings(listDimensions: Sequence[int], computationDivisions: Optional[Union[int, str]] = None, CPUlimit: Optional[Union[bool, float, int]] = None, **keywordArguments: Optional[Type]) -> computationState:
|
|
325
|
+
datatypeMedium = keywordArguments.get('datatypeMedium', dtypeMedium)
|
|
326
|
+
datatypeLarge = keywordArguments.get('datatypeLarge', dtypeLarge)
|
|
327
|
+
|
|
328
|
+
the = makeDataContainer(len(indexThe), datatypeMedium)
|
|
329
|
+
|
|
330
|
+
mapShape = tuple(sorted(validateListDimensions(listDimensions)))
|
|
331
|
+
the[indexThe.leavesTotal] = getLeavesTotal(mapShape)
|
|
332
|
+
the[indexThe.dimensionsTotal] = len(mapShape)
|
|
333
|
+
concurrencyLimit = setCPUlimit(CPUlimit)
|
|
334
|
+
the[indexThe.taskDivisions] = getTaskDivisions(computationDivisions, concurrencyLimit, CPUlimit, listDimensions)
|
|
335
|
+
|
|
336
|
+
stateInitialized = computationState(
|
|
337
|
+
connectionGraph = makeConnectionGraph(mapShape, datatype=datatypeMedium),
|
|
338
|
+
foldsSubTotals = makeDataContainer(the[indexThe.leavesTotal], datatypeLarge),
|
|
339
|
+
mapShape = mapShape,
|
|
340
|
+
my = makeDataContainer(len(indexMy), datatypeLarge),
|
|
341
|
+
gapsWhere = makeDataContainer(int(the[indexThe.leavesTotal]) * int(the[indexThe.leavesTotal]) + 1, datatypeMedium),
|
|
342
|
+
the = the,
|
|
343
|
+
track = makeDataContainer((len(indexTrack), the[indexThe.leavesTotal] + 1), datatypeLarge)
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
stateInitialized['my'][indexMy.leaf1ndex] = 1
|
|
347
|
+
return stateInitialized
|
|
348
|
+
|
|
349
|
+
def parseDimensions(dimensions: Sequence[int], parameterName: str = 'unnamed parameter') -> List[int]:
|
|
350
|
+
# listValidated = intInnit(dimensions, parameterName)
|
|
351
|
+
listNOTValidated = dimensions if isinstance(dimensions, (list, tuple)) else list(dimensions)
|
|
352
|
+
listNonNegative = []
|
|
353
|
+
for dimension in listNOTValidated:
|
|
354
|
+
if dimension < 0:
|
|
355
|
+
raise ValueError(f"Dimension {dimension} must be non-negative")
|
|
356
|
+
listNonNegative.append(dimension)
|
|
357
|
+
if not listNonNegative:
|
|
358
|
+
raise ValueError("At least one dimension must be non-negative")
|
|
359
|
+
return listNonNegative
|
|
360
|
+
|
|
361
|
+
def setCPUlimit(CPUlimit: Union[bool, float, int, None]) -> int:
|
|
362
|
+
# if not (CPUlimit is None or isinstance(CPUlimit, (bool, int, float))):
|
|
363
|
+
# CPUlimit = oopsieKwargsie(CPUlimit)
|
|
364
|
+
# concurrencyLimit = defineConcurrencyLimit(CPUlimit)
|
|
365
|
+
# numba.set_num_threads(concurrencyLimit)
|
|
366
|
+
concurrencyLimitHARDCODED = 1
|
|
367
|
+
concurrencyLimit = concurrencyLimitHARDCODED
|
|
368
|
+
return concurrencyLimit
|
|
369
|
+
|
|
370
|
+
def validateListDimensions(listDimensions: Sequence[int]) -> List[int]:
|
|
371
|
+
if not listDimensions:
|
|
372
|
+
raise ValueError(f"listDimensions is a required parameter.")
|
|
373
|
+
listNonNegative = parseDimensions(listDimensions, 'listDimensions')
|
|
374
|
+
dimensionsValid = [dimension for dimension in listNonNegative if dimension > 0]
|
|
375
|
+
if len(dimensionsValid) < 2:
|
|
376
|
+
raise NotImplementedError(f"This function requires listDimensions, {listDimensions}, to have at least two dimensions greater than 0. You may want to look at https://oeis.org/.")
|
|
377
|
+
return sorted(dimensionsValid)
|