mapFolding 0.6.0__tar.gz → 0.7.0__tar.gz

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.
Files changed (67) hide show
  1. {mapfolding-0.6.0 → mapfolding-0.7.0}/PKG-INFO +7 -6
  2. mapfolding-0.7.0/mapFolding/__init__.py +9 -0
  3. {mapfolding-0.6.0 → mapfolding-0.7.0}/mapFolding/basecamp.py +12 -8
  4. mapfolding-0.7.0/mapFolding/beDRY.py +164 -0
  5. mapfolding-0.7.0/mapFolding/filesystem.py +87 -0
  6. mapfolding-0.7.0/mapFolding/noHomeYet.py +20 -0
  7. {mapfolding-0.6.0 → mapfolding-0.7.0}/mapFolding/oeis.py +46 -39
  8. mapfolding-0.7.0/mapFolding/reference/flattened.py +377 -0
  9. mapfolding-0.7.0/mapFolding/reference/hunterNumba.py +132 -0
  10. mapfolding-0.7.0/mapFolding/reference/irvineJavaPort.py +120 -0
  11. mapfolding-0.7.0/mapFolding/reference/jax.py +208 -0
  12. mapfolding-0.7.0/mapFolding/reference/lunnan.py +153 -0
  13. mapfolding-0.7.0/mapFolding/reference/lunnanNumpy.py +123 -0
  14. mapfolding-0.7.0/mapFolding/reference/lunnanWhile.py +121 -0
  15. mapfolding-0.7.0/mapFolding/reference/rotatedEntryPoint.py +240 -0
  16. mapfolding-0.7.0/mapFolding/reference/total_countPlus1vsPlusN.py +211 -0
  17. mapfolding-0.7.0/mapFolding/someAssemblyRequired/Z0Z_workbench.py +34 -0
  18. mapfolding-0.7.0/mapFolding/someAssemblyRequired/__init__.py +16 -0
  19. mapfolding-0.7.0/mapFolding/someAssemblyRequired/getLLVMforNoReason.py +21 -0
  20. mapfolding-0.7.0/mapFolding/someAssemblyRequired/ingredientsNumba.py +100 -0
  21. mapfolding-0.7.0/mapFolding/someAssemblyRequired/synthesizeCountingFunctions.py +7 -0
  22. mapfolding-0.7.0/mapFolding/someAssemblyRequired/synthesizeDataConverters.py +135 -0
  23. mapfolding-0.7.0/mapFolding/someAssemblyRequired/synthesizeNumba.py +91 -0
  24. mapfolding-0.7.0/mapFolding/someAssemblyRequired/synthesizeNumbaJob.py +417 -0
  25. mapfolding-0.7.0/mapFolding/someAssemblyRequired/synthesizeNumbaModules.py +91 -0
  26. mapfolding-0.7.0/mapFolding/someAssemblyRequired/transformationTools.py +425 -0
  27. mapfolding-0.7.0/mapFolding/someAssemblyRequired/whatWillBe.py +311 -0
  28. mapfolding-0.7.0/mapFolding/syntheticModules/__init__.py +0 -0
  29. mapfolding-0.7.0/mapFolding/syntheticModules/dataNamespaceFlattened.py +30 -0
  30. mapfolding-0.7.0/mapFolding/syntheticModules/numbaCount.py +90 -0
  31. mapfolding-0.7.0/mapFolding/syntheticModules/numbaCountExample.py +158 -0
  32. mapfolding-0.7.0/mapFolding/syntheticModules/numbaCountSequential.py +110 -0
  33. mapfolding-0.7.0/mapFolding/syntheticModules/numbaCount_doTheNeedful.py +13 -0
  34. mapfolding-0.7.0/mapFolding/syntheticModules/numba_doTheNeedful.py +12 -0
  35. mapfolding-0.7.0/mapFolding/syntheticModules/numba_doTheNeedfulExample.py +13 -0
  36. mapfolding-0.7.0/mapFolding/theDao.py +208 -0
  37. mapfolding-0.7.0/mapFolding/theSSOT.py +273 -0
  38. {mapfolding-0.6.0 → mapfolding-0.7.0}/mapFolding.egg-info/PKG-INFO +7 -6
  39. mapfolding-0.7.0/mapFolding.egg-info/SOURCES.txt +97 -0
  40. {mapfolding-0.6.0 → mapfolding-0.7.0}/mapFolding.egg-info/requires.txt +5 -4
  41. mapfolding-0.7.0/mapFolding.egg-info/top_level.txt +5 -0
  42. {mapfolding-0.6.0 → mapfolding-0.7.0}/pyproject.toml +15 -9
  43. mapfolding-0.7.0/tests/__init__.py +0 -0
  44. mapfolding-0.7.0/tests/conftest.py +278 -0
  45. mapfolding-0.7.0/tests/test_computations.py +49 -0
  46. mapfolding-0.7.0/tests/test_filesystem.py +52 -0
  47. {mapfolding-0.6.0 → mapfolding-0.7.0}/tests/test_oeis.py +12 -20
  48. mapfolding-0.7.0/tests/test_other.py +84 -0
  49. mapfolding-0.7.0/tests/test_tasks.py +50 -0
  50. mapfolding-0.6.0/mapFolding/__init__.py +0 -107
  51. mapfolding-0.6.0/mapFolding/beDRY.py +0 -354
  52. mapfolding-0.6.0/mapFolding/theConfiguration.py +0 -58
  53. mapfolding-0.6.0/mapFolding/theDao.py +0 -232
  54. mapfolding-0.6.0/mapFolding/theSSOT.py +0 -120
  55. mapfolding-0.6.0/mapFolding/theSSOTdatatypes.py +0 -155
  56. mapfolding-0.6.0/mapFolding/theWrongWay.py +0 -7
  57. mapfolding-0.6.0/mapFolding.egg-info/SOURCES.txt +0 -33
  58. mapfolding-0.6.0/mapFolding.egg-info/top_level.txt +0 -1
  59. mapfolding-0.6.0/tests/test_computations.py +0 -52
  60. mapfolding-0.6.0/tests/test_other.py +0 -190
  61. mapfolding-0.6.0/tests/test_tasks.py +0 -41
  62. {mapfolding-0.6.0 → mapfolding-0.7.0}/LICENSE +0 -0
  63. {mapfolding-0.6.0 → mapfolding-0.7.0}/README.md +0 -0
  64. {mapfolding-0.6.0 → mapfolding-0.7.0}/mapFolding/py.typed +0 -0
  65. {mapfolding-0.6.0 → mapfolding-0.7.0}/mapFolding.egg-info/dependency_links.txt +0 -0
  66. {mapfolding-0.6.0 → mapfolding-0.7.0}/mapFolding.egg-info/entry_points.txt +0 -0
  67. {mapfolding-0.6.0 → mapfolding-0.7.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: mapFolding
3
- Version: 0.6.0
3
+ Version: 0.7.0
4
4
  Summary: Count distinct ways to fold a map (or a strip of stamps)
5
5
  Author-email: Hunter Hogan <HunterHogan@pm.me>
6
6
  License: CC-BY-NC-4.0
@@ -8,7 +8,7 @@ Project-URL: Donate, https://www.patreon.com/integrated
8
8
  Project-URL: Homepage, https://github.com/hunterhogan/mapFolding
9
9
  Project-URL: Repository, https://github.com/hunterhogan/mapFolding.git
10
10
  Keywords: A001415,A001416,A001417,A001418,A195646,combinatorics,folding,map folding,OEIS,optimization,stamp folding
11
- Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Environment :: Console
13
13
  Classifier: Intended Audience :: Education
14
14
  Classifier: Intended Audience :: End Users/Desktop
@@ -28,19 +28,20 @@ Classifier: Typing :: Typed
28
28
  Requires-Python: >=3.10
29
29
  Description-Content-Type: text/markdown
30
30
  License-File: LICENSE
31
+ Requires-Dist: autoflake
32
+ Requires-Dist: more_itertools
33
+ Requires-Dist: numba_progress
31
34
  Requires-Dist: numba
32
35
  Requires-Dist: numpy
36
+ Requires-Dist: python_minifier
37
+ Requires-Dist: tomli
33
38
  Requires-Dist: Z0Z_tools
34
39
  Provides-Extra: testing
35
- Requires-Dist: autoflake; extra == "testing"
36
40
  Requires-Dist: mypy; extra == "testing"
37
- Requires-Dist: more_itertools; extra == "testing"
38
- Requires-Dist: numba_progress; extra == "testing"
39
41
  Requires-Dist: pytest-cov; extra == "testing"
40
42
  Requires-Dist: pytest-env; extra == "testing"
41
43
  Requires-Dist: pytest-xdist; extra == "testing"
42
44
  Requires-Dist: pytest; extra == "testing"
43
- Requires-Dist: python_minifier; extra == "testing"
44
45
  Requires-Dist: pyupgrade; extra == "testing"
45
46
  Requires-Dist: updateCitation; extra == "testing"
46
47
 
@@ -0,0 +1,9 @@
1
+ from mapFolding.basecamp import countFolds
2
+ from mapFolding.oeis import clearOEIScache, getOEISids, OEIS_for_n
3
+
4
+ __all__ = [
5
+ 'clearOEIScache',
6
+ 'countFolds',
7
+ 'getOEISids',
8
+ 'OEIS_for_n',
9
+ ]
@@ -1,5 +1,7 @@
1
1
  from collections.abc import Sequence
2
- from mapFolding import computationState, getDispatcherCallable, getPathFilenameFoldsTotal, outfitCountFolds, saveFoldsTotal
2
+ from mapFolding.beDRY import outfitCountFolds, setCPUlimit, validateListDimensions
3
+ from mapFolding.filesystem import getPathFilenameFoldsTotal, saveFoldsTotal
4
+ from mapFolding.theSSOT import ComputationState, getPackageDispatcher
3
5
  from os import PathLike
4
6
  from pathlib import Path
5
7
 
@@ -37,15 +39,17 @@ def countFolds(listDimensions: Sequence[int]
37
39
  N.B.: You probably don't want to divide the computation into tasks.
38
40
  If you want to compute a large `foldsTotal`, dividing the computation into tasks is usually a bad idea. Dividing the algorithm into tasks is inherently inefficient: efficient division into tasks means there would be no overlap in the work performed by each task. When dividing this algorithm, the amount of overlap is between 50% and 90% by all tasks: at least 50% of the work done by every task must be done by _all_ tasks. If you improve the computation time, it will only change by -10 to -50% depending on (at the very least) the ratio of the map dimensions and the number of leaves. If an undivided computation would take 10 hours on your computer, for example, the computation will still take at least 5 hours but you might reduce the time to 9 hours. Most of the time, however, you will increase the computation time. If logicalCores >= leavesTotal, it will probably be faster. If logicalCores <= 2 * leavesTotal, it will almost certainly be slower for all map dimensions.
39
41
  """
40
- stateUniversal: computationState = outfitCountFolds(listDimensions, computationDivisions=computationDivisions, CPUlimit=CPUlimit)
42
+ mapShape: tuple[int, ...] = validateListDimensions(listDimensions)
43
+ concurrencyLimit: int = setCPUlimit(CPUlimit)
44
+ computationStateInitialized: ComputationState = outfitCountFolds(mapShape, computationDivisions, concurrencyLimit)
41
45
 
42
- dispatcher = getDispatcherCallable()
43
- dispatcher(**stateUniversal)
46
+ dispatcher = getPackageDispatcher()
47
+ computationStateComplete: ComputationState = dispatcher(computationStateInitialized)
44
48
 
45
- foldsTotal = int(stateUniversal['foldGroups'][0:-1].sum() * stateUniversal['foldGroups'][-1])
49
+ computationStateComplete.getFoldsTotal()
46
50
 
47
51
  if pathLikeWriteFoldsTotal is not None:
48
- pathFilenameFoldsTotal: Path = getPathFilenameFoldsTotal(stateUniversal['mapShape'], pathLikeWriteFoldsTotal)
49
- saveFoldsTotal(pathFilenameFoldsTotal, foldsTotal)
52
+ pathFilenameFoldsTotal: Path = getPathFilenameFoldsTotal(computationStateComplete.mapShape, pathLikeWriteFoldsTotal)
53
+ saveFoldsTotal(pathFilenameFoldsTotal, computationStateComplete.foldsTotal)
50
54
 
51
- return foldsTotal
55
+ return computationStateComplete.foldsTotal
@@ -0,0 +1,164 @@
1
+ """A relatively stable API for oft-needed functionality."""
2
+ from mapFolding.theSSOT import (
3
+ Array3D,
4
+ ComputationState,
5
+ getDatatypePackage,
6
+ getNumpyDtypeDefault,
7
+ )
8
+ from collections.abc import Sequence
9
+ from sys import maxsize as sysMaxsize
10
+ from typing import Any
11
+ from Z0Z_tools import defineConcurrencyLimit, intInnit, oopsieKwargsie
12
+ import numpy
13
+
14
+ def validateListDimensions(listDimensions: Sequence[int]) -> tuple[int, ...]:
15
+ if not listDimensions:
16
+ raise ValueError("listDimensions is a required parameter.")
17
+ listValidated: list[int] = intInnit(listDimensions, 'listDimensions')
18
+ listNonNegative: list[int] = []
19
+ for dimension in listValidated:
20
+ if dimension < 0:
21
+ raise ValueError(f"Dimension {dimension} must be non-negative")
22
+ listNonNegative.append(dimension)
23
+ dimensionsValid = [dimension for dimension in listNonNegative if dimension > 0]
24
+ if len(dimensionsValid) < 2:
25
+ 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/.")
26
+ return tuple(sorted(dimensionsValid))
27
+
28
+ def getLeavesTotal(mapShape: tuple[int, ...]) -> int:
29
+ productDimensions = 1
30
+ for dimension in mapShape:
31
+ if dimension > sysMaxsize // productDimensions:
32
+ raise OverflowError(f"I received {dimension=} in {mapShape=}, but the product of the dimensions exceeds the maximum size of an integer on this system.")
33
+ productDimensions *= dimension
34
+ return productDimensions
35
+
36
+ def getNumpyDtype(datatype: type[numpy.signedinteger[Any]] | None = None) -> type[numpy.signedinteger[Any]]:
37
+ """An imperfect way to reduce code duplication."""
38
+ if 'numpy' == getDatatypePackage():
39
+ numpyDtype = datatype or getNumpyDtypeDefault()
40
+ else:
41
+ raise NotImplementedError("Somebody done broke it.")
42
+ return numpyDtype
43
+
44
+ def makeConnectionGraph(mapShape: tuple[int, ...], leavesTotal: int, datatype: type[numpy.signedinteger[Any]] | None = None) -> Array3D:
45
+ numpyDtype = getNumpyDtype(datatype)
46
+ dimensionsTotal = len(mapShape)
47
+ cumulativeProduct = numpy.multiply.accumulate([1] + list(mapShape), dtype=numpyDtype)
48
+ arrayDimensions = numpy.array(mapShape, dtype=numpyDtype)
49
+ coordinateSystem = numpy.zeros((dimensionsTotal, leavesTotal + 1), dtype=numpyDtype)
50
+ for indexDimension in range(dimensionsTotal):
51
+ for leaf1ndex in range(1, leavesTotal + 1):
52
+ coordinateSystem[indexDimension, leaf1ndex] = (((leaf1ndex - 1) // cumulativeProduct[indexDimension]) % arrayDimensions[indexDimension] + 1)
53
+
54
+ connectionGraph = numpy.zeros((dimensionsTotal, leavesTotal + 1, leavesTotal + 1), dtype=numpyDtype)
55
+ for indexDimension in range(dimensionsTotal):
56
+ for activeLeaf1ndex in range(1, leavesTotal + 1):
57
+ for connectee1ndex in range(1, activeLeaf1ndex + 1):
58
+ isFirstCoord = coordinateSystem[indexDimension, connectee1ndex] == 1
59
+ isLastCoord = coordinateSystem[indexDimension, connectee1ndex] == arrayDimensions[indexDimension]
60
+ exceedsActive = connectee1ndex + cumulativeProduct[indexDimension] > activeLeaf1ndex
61
+ isEvenParity = (coordinateSystem[indexDimension, activeLeaf1ndex] & 1) == (coordinateSystem[indexDimension, connectee1ndex] & 1)
62
+
63
+ if (isEvenParity and isFirstCoord) or (not isEvenParity and (isLastCoord or exceedsActive)):
64
+ connectionGraph[indexDimension, activeLeaf1ndex, connectee1ndex] = connectee1ndex
65
+ elif isEvenParity and not isFirstCoord:
66
+ connectionGraph[indexDimension, activeLeaf1ndex, connectee1ndex] = connectee1ndex - cumulativeProduct[indexDimension]
67
+ elif not isEvenParity and not (isLastCoord or exceedsActive):
68
+ connectionGraph[indexDimension, activeLeaf1ndex, connectee1ndex] = connectee1ndex + cumulativeProduct[indexDimension]
69
+ return connectionGraph
70
+
71
+ def makeDataContainer(shape: int | tuple[int, ...], datatype: type[numpy.signedinteger[Any]] | None = None) -> numpy.ndarray[Any, numpy.dtype[numpy.signedinteger[Any]]]:
72
+ numpyDtype = getNumpyDtype(datatype)
73
+ return numpy.zeros(shape, dtype=numpyDtype)
74
+
75
+ def setCPUlimit(CPUlimit: Any | None) -> int:
76
+ """Sets CPU limit for Numba concurrent operations. Note that it can only affect Numba-jitted functions that have not yet been imported.
77
+
78
+ Parameters:
79
+ CPUlimit: whether and how to limit the CPU usage. See notes for details.
80
+ Returns:
81
+ concurrencyLimit: The actual concurrency limit that was set
82
+ Raises:
83
+ TypeError: If CPUlimit is not of the expected types
84
+
85
+ Limits on CPU usage `CPUlimit`:
86
+ - `False`, `None`, or `0`: No limits on CPU usage; uses all available CPUs. All other values will potentially limit CPU usage.
87
+ - `True`: Yes, limit the CPU usage; limits to 1 CPU.
88
+ - Integer `>= 1`: Limits usage to the specified number of CPUs.
89
+ - Decimal value (`float`) between 0 and 1: Fraction of total CPUs to use.
90
+ - Decimal value (`float`) between -1 and 0: Fraction of CPUs to *not* use.
91
+ - Integer `<= -1`: Subtract the absolute value from total CPUs.
92
+ """
93
+ if not (CPUlimit is None or isinstance(CPUlimit, (bool, int, float))):
94
+ CPUlimit = oopsieKwargsie(CPUlimit)
95
+
96
+ concurrencyLimit: int = int(defineConcurrencyLimit(CPUlimit))
97
+ from mapFolding.theSSOT import concurrencyPackage
98
+ if concurrencyPackage == 'numba':
99
+ from numba import get_num_threads, set_num_threads
100
+ set_num_threads(concurrencyLimit)
101
+ concurrencyLimit = get_num_threads()
102
+ elif concurrencyPackage == 'algorithm':
103
+ concurrencyLimit = 1
104
+ else:
105
+ raise NotImplementedError("This function only supports the 'numba' concurrency package.")
106
+
107
+ return concurrencyLimit
108
+
109
+ def getTaskDivisions(computationDivisions: int | str | None, concurrencyLimit: int, leavesTotal: int) -> int:
110
+ """
111
+ Determines whether to divide the computation into tasks and how many divisions.
112
+
113
+ Parameters
114
+ ----------
115
+ computationDivisions (None)
116
+ Specifies how to divide computations:
117
+ - `None`: no division of the computation into tasks; sets task divisions to 0.
118
+ - int: direct set the number of task divisions; cannot exceed the map's total leaves.
119
+ - `'maximum'`: divides into `leavesTotal`-many `taskDivisions`.
120
+ - `'cpu'`: limits the divisions to the number of available CPUs, i.e. `concurrencyLimit`.
121
+ concurrencyLimit
122
+ Maximum number of concurrent tasks allowed.
123
+ CPUlimit
124
+ for error reporting.
125
+ listDimensions
126
+ for error reporting.
127
+
128
+ Returns
129
+ -------
130
+ taskDivisions
131
+ How many tasks must finish before the job can compute the total number of folds; `0` means no tasks, only job.
132
+
133
+ Raises
134
+ ------
135
+ ValueError
136
+ If computationDivisions is an unsupported type or if resulting task divisions exceed total leaves.
137
+
138
+ Notes
139
+ -----
140
+ Task divisions should not exceed total leaves or the folds will be over-counted.
141
+ """
142
+ taskDivisions = 0
143
+ if not computationDivisions:
144
+ pass
145
+ elif isinstance(computationDivisions, int):
146
+ taskDivisions = computationDivisions
147
+ elif isinstance(computationDivisions, str): # type: ignore 'Unnecessary isinstance call; "str" is always an instance of "str", so sayeth Pylance'. Yeah, well "User is not always an instance of "correct input" so sayeth the programmer.
148
+ computationDivisions = computationDivisions.lower()
149
+ if computationDivisions == 'maximum':
150
+ taskDivisions = leavesTotal
151
+ elif computationDivisions == 'cpu':
152
+ taskDivisions = min(concurrencyLimit, leavesTotal)
153
+ else:
154
+ raise ValueError(f"I received {computationDivisions} for the parameter, `computationDivisions`, but the so-called programmer didn't implement code for that.")
155
+
156
+ if taskDivisions > leavesTotal:
157
+ raise ValueError(f"Problem: `taskDivisions`, ({taskDivisions}), is greater than `leavesTotal`, ({leavesTotal}), which will cause duplicate counting of the folds.\n\nChallenge: you cannot directly set `taskDivisions` or `leavesTotal`. They are derived from parameters that may or may not still be named `computationDivisions`, `CPUlimit` , and `listDimensions` and from dubious-quality Python code.")
158
+ return int(max(0, taskDivisions))
159
+
160
+ def outfitCountFolds(mapShape: tuple[int, ...], computationDivisions: int | str | None = None, concurrencyLimit: int = 1) -> ComputationState:
161
+ leavesTotal = getLeavesTotal(mapShape)
162
+ taskDivisions = getTaskDivisions(computationDivisions, concurrencyLimit, leavesTotal)
163
+ computationStateInitialized = ComputationState(mapShape, leavesTotal, taskDivisions)
164
+ return computationStateInitialized
@@ -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
@@ -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)
@@ -1,9 +1,9 @@
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 countFolds, pathPackage
4
+ from mapFolding.theSSOT import thePathPackage
5
5
  from pathlib import Path
6
- from typing import Any, cast, Final, TYPE_CHECKING
6
+ from typing import Any, Final, TYPE_CHECKING
7
7
  import argparse
8
8
  import pathlib
9
9
  import random
@@ -23,11 +23,11 @@ cacheDays = 7
23
23
  """
24
24
  Section: make `settingsOEIS`"""
25
25
 
26
- pathCache: Path = pathPackage / ".cache"
26
+ pathCache: Path = thePathPackage / ".cache"
27
27
 
28
28
  class SettingsOEIS(TypedDict):
29
29
  description: str
30
- getMapShape: Callable[[int], list[int]]
30
+ getMapShape: Callable[[int], tuple[int, ...]]
31
31
  offset: int
32
32
  valuesBenchmark: list[int]
33
33
  valuesKnown: dict[int, int]
@@ -35,38 +35,45 @@ class SettingsOEIS(TypedDict):
35
35
  valuesTestValidation: list[int]
36
36
  valueUnknown: int
37
37
 
38
- settingsOEIShardcodedValues: dict[str, dict[str, Any]] = {
39
- 'A001415': {
40
- 'getMapShape': cast(Callable[[int], list[int]], lambda n: sorted([2, n])), # type: ignore
41
- 'valuesBenchmark': [14],
42
- 'valuesTestParallelization': [*range(3, 7)],
43
- 'valuesTestValidation': [random.randint(2, 9)],
44
- },
45
- 'A001416': {
46
- 'getMapShape': cast(Callable[[int], list[int]], lambda n: sorted([3, n])), # type: ignore
47
- 'valuesBenchmark': [9],
48
- 'valuesTestParallelization': [*range(3, 5)],
49
- 'valuesTestValidation': [random.randint(2, 6)],
50
- },
51
- 'A001417': {
52
- 'getMapShape': cast(Callable[[int], list[int]], lambda n: [2] * n), # type: ignore
53
- 'valuesBenchmark': [6],
54
- 'valuesTestParallelization': [*range(2, 4)],
55
- 'valuesTestValidation': [random.randint(2, 4)],
56
- },
57
- 'A195646': {
58
- 'getMapShape': cast(Callable[[int], list[int]], lambda n: [3] * n), # type: ignore
59
- 'valuesBenchmark': [3],
60
- 'valuesTestParallelization': [*range(2, 3)],
61
- 'valuesTestValidation': [2],
62
- },
63
- 'A001418': {
64
- 'getMapShape': cast(Callable[[int], list[int]], lambda n: [n, n]), # type: ignore
65
- 'valuesBenchmark': [5],
66
- 'valuesTestParallelization': [*range(2, 4)],
67
- 'valuesTestValidation': [random.randint(2, 4)],
68
- },
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] = {
45
+ 'A001415': {
46
+ 'getMapShape': lambda n: (2, n) if n >= 2 else (n, 2),
47
+ 'valuesBenchmark': [14],
48
+ 'valuesTestParallelization': [*range(3, 7)],
49
+ 'valuesTestValidation': [random.randint(2, 9)],
50
+ },
51
+ 'A001416': {
52
+ 'getMapShape': lambda n: (3, n) if n >= 3 else (n, 3),
53
+ 'valuesBenchmark': [9],
54
+ 'valuesTestParallelization': [*range(3, 5)],
55
+ 'valuesTestValidation': [random.randint(2, 6)],
56
+ },
57
+ 'A001417': {
58
+ 'getMapShape': lambda n: tuple(2 for _dimension in range(n)),
59
+ 'valuesBenchmark': [6],
60
+ 'valuesTestParallelization': [*range(2, 4)],
61
+ 'valuesTestValidation': [random.randint(2, 4)],
62
+ },
63
+ 'A195646': {
64
+ 'getMapShape': lambda n: tuple(3 for _dimension in range(n)),
65
+ 'valuesBenchmark': [3],
66
+ 'valuesTestParallelization': [*range(2, 3)],
67
+ 'valuesTestValidation': [2],
68
+ },
69
+ 'A001418': {
70
+ 'getMapShape': lambda n: (n, n),
71
+ 'valuesBenchmark': [5],
72
+ 'valuesTestParallelization': [*range(2, 4)],
73
+ 'valuesTestValidation': [random.randint(2, 4)],
74
+ },
69
75
  }
76
+
70
77
  oeisIDsImplemented: Final[list[str]] = sorted([oeisID.upper().strip() for oeisID in settingsOEIShardcodedValues.keys()])
71
78
  """Directly implemented OEIS IDs; standardized, e.g., 'A001415'."""
72
79
 
@@ -286,16 +293,16 @@ def oeisIDfor_n(oeisID: str, n: int | Any) -> int:
286
293
  if not isinstance(n, int) or n < 0:
287
294
  raise ValueError("`n` must be non-negative integer.")
288
295
 
289
- listDimensions: list[int] = settingsOEIS[oeisID]['getMapShape'](n)
296
+ mapShape: tuple[int, ...] = settingsOEIS[oeisID]['getMapShape'](n)
290
297
 
291
- if n <= 1 or len(listDimensions) < 2:
298
+ if n <= 1 or len(mapShape) < 2:
292
299
  offset: int = settingsOEIS[oeisID]['offset']
293
300
  if n < offset:
294
301
  raise ArithmeticError(f"OEIS sequence {oeisID} is not defined at n={n}.")
295
302
  foldsTotal: int = settingsOEIS[oeisID]['valuesKnown'][n]
296
303
  return foldsTotal
297
-
298
- return countFolds(listDimensions)
304
+ from mapFolding.basecamp import countFolds
305
+ return countFolds(mapShape)
299
306
 
300
307
  def OEIS_for_n() -> None:
301
308
  """Command-line interface for oeisIDfor_n."""