mapFolding 0.3.8__py3-none-any.whl → 0.3.10__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.
Files changed (48) hide show
  1. mapFolding/__init__.py +56 -0
  2. mapFolding/basecamp.py +55 -0
  3. mapFolding/beDRY.py +376 -0
  4. mapFolding/oeis.py +339 -0
  5. mapFolding/someAssemblyRequired/__init__.py +2 -0
  6. {someAssemblyRequired → mapFolding/someAssemblyRequired}/makeJob.py +4 -5
  7. mapFolding/someAssemblyRequired/synthesizeJobNumba.py +383 -0
  8. mapFolding/someAssemblyRequired/synthesizeModuleJAX.py +29 -0
  9. {someAssemblyRequired → mapFolding/someAssemblyRequired}/synthesizeModulesNumba.py +186 -99
  10. syntheticModules/numbaInitialize.py → mapFolding/syntheticModules/numba_countInitialize.py +6 -9
  11. syntheticModules/numbaParallel.py → mapFolding/syntheticModules/numba_countParallel.py +4 -4
  12. syntheticModules/numbaSequential.py → mapFolding/syntheticModules/numba_countSequential.py +5 -5
  13. mapFolding/syntheticModules/numba_doTheNeedful.py +30 -0
  14. mapFolding/theDao.py +213 -0
  15. mapFolding/theSSOT.py +251 -0
  16. mapFolding/theSSOTnumba.py +115 -0
  17. mapFolding-0.3.10.dist-info/LICENSE +407 -0
  18. {mapFolding-0.3.8.dist-info → mapFolding-0.3.10.dist-info}/METADATA +9 -11
  19. mapFolding-0.3.10.dist-info/RECORD +40 -0
  20. mapFolding-0.3.10.dist-info/top_level.txt +2 -0
  21. tests/__init__.py +1 -0
  22. tests/conftest.py +183 -0
  23. tests/conftest_tmpRegistry.py +62 -0
  24. tests/conftest_uniformTests.py +53 -0
  25. tests/test_oeis.py +141 -0
  26. tests/test_other.py +259 -0
  27. tests/test_tasks.py +44 -0
  28. tests/test_types.py +5 -0
  29. benchmarks/benchmarking.py +0 -67
  30. citations/constants.py +0 -3
  31. citations/updateCitation.py +0 -354
  32. mapFolding-0.3.8.dist-info/RECORD +0 -26
  33. mapFolding-0.3.8.dist-info/top_level.txt +0 -5
  34. someAssemblyRequired/__init__.py +0 -1
  35. someAssemblyRequired/synthesizeModuleJobNumba.py +0 -212
  36. syntheticModules/__init__.py +0 -3
  37. {reference → mapFolding/reference}/flattened.py +0 -0
  38. {reference → mapFolding/reference}/hunterNumba.py +0 -0
  39. {reference → mapFolding/reference}/irvineJavaPort.py +0 -0
  40. {reference → mapFolding/reference}/jax.py +0 -0
  41. {reference → mapFolding/reference}/lunnan.py +0 -0
  42. {reference → mapFolding/reference}/lunnanNumpy.py +0 -0
  43. {reference → mapFolding/reference}/lunnanWhile.py +0 -0
  44. {reference → mapFolding/reference}/rotatedEntryPoint.py +0 -0
  45. {reference → mapFolding/reference}/total_countPlus1vsPlusN.py +0 -0
  46. {someAssemblyRequired → mapFolding/someAssemblyRequired}/getLLVMforNoReason.py +0 -0
  47. {mapFolding-0.3.8.dist-info → mapFolding-0.3.10.dist-info}/WHEEL +0 -0
  48. {mapFolding-0.3.8.dist-info → mapFolding-0.3.10.dist-info}/entry_points.txt +0 -0
mapFolding/__init__.py ADDED
@@ -0,0 +1,56 @@
1
+ # fundamentals
2
+ from mapFolding.theSSOT import (
3
+ computationState,
4
+ EnumIndices,
5
+ getDispatcherCallable,
6
+ getPathPackage,
7
+ indexMy,
8
+ indexTrack,
9
+ myPackageNameIs,
10
+ )
11
+
12
+ # Datatype management
13
+ from mapFolding.theSSOT import (
14
+ hackSSOTdatatype,
15
+ hackSSOTdtype,
16
+ setDatatypeElephino,
17
+ setDatatypeFoldsTotal,
18
+ setDatatypeLeavesTotal,
19
+ setDatatypeModule,
20
+ )
21
+
22
+ # Synthesize modules
23
+ from mapFolding.theSSOT import (
24
+ getAlgorithmCallable,
25
+ getAlgorithmSource,
26
+ getPathJobRootDEFAULT,
27
+ getPathSyntheticModules,
28
+ moduleOfSyntheticModules,
29
+ )
30
+
31
+ # Parameters for the prima donna
32
+ from mapFolding.theSSOT import (
33
+ ParametersNumba,
34
+ parametersNumbaDEFAULT,
35
+ parametersNumbaFailEarly,
36
+ parametersNumbaParallelDEFAULT,
37
+ parametersNumbaSuperJit,
38
+ parametersNumbaSuperJitParallel,
39
+ )
40
+
41
+ from mapFolding.beDRY import (
42
+ getFilenameFoldsTotal,
43
+ getPathFilenameFoldsTotal,
44
+ outfitCountFolds,
45
+ saveFoldsTotal,
46
+ )
47
+
48
+ from mapFolding.basecamp import countFolds
49
+ from mapFolding.oeis import clearOEIScache, getOEISids, oeisIDfor_n
50
+
51
+ __all__ = [
52
+ 'clearOEIScache',
53
+ 'countFolds',
54
+ 'getOEISids',
55
+ 'oeisIDfor_n',
56
+ ]
mapFolding/basecamp.py ADDED
@@ -0,0 +1,55 @@
1
+ from mapFolding import computationState, getDispatcherCallable, getPathFilenameFoldsTotal, outfitCountFolds, saveFoldsTotal
2
+ from typing import Optional, Sequence, Union
3
+ import os
4
+
5
+ def countFolds(listDimensions: Sequence[int]
6
+ , pathLikeWriteFoldsTotal: Optional[Union[str, os.PathLike[str]]] = None
7
+ , computationDivisions: Optional[Union[int, str]] = None
8
+ , CPUlimit: Optional[Union[int, float, bool]] = None
9
+ , **keywordArguments: Optional[Union[str, bool]]
10
+ ) -> int:
11
+ """Count the total number of possible foldings for a given map dimensions.
12
+
13
+ Parameters:
14
+ listDimensions: List of integers representing the dimensions of the map to be folded.
15
+ pathLikeWriteFoldsTotal (None): Path, filename, or pathFilename to write the total fold count to.
16
+ If a directory is provided, creates a file with a default name based on map dimensions.
17
+ computationDivisions (None):
18
+ Whether and how to divide the computational work. See notes for details.
19
+ CPUlimit (None): This is only relevant if there are `computationDivisions`: whether and how to limit the CPU usage. See notes for details.
20
+ **keywordArguments: Datatype management.
21
+ Returns:
22
+ foldsTotal: Total number of distinct ways to fold a map of the given dimensions.
23
+
24
+ Computation divisions:
25
+ - None: no division of the computation into tasks; sets task divisions to 0
26
+ - int: direct set the number of task divisions; cannot exceed the map's total leaves
27
+ - "maximum": divides into `leavesTotal`-many `taskDivisions`
28
+ - "cpu": limits the divisions to the number of available CPUs, i.e. `concurrencyLimit`
29
+
30
+ Limits on CPU usage `CPUlimit`:
31
+ - `False`, `None`, or `0`: No limits on CPU usage; uses all available CPUs. All other values will potentially limit CPU usage.
32
+ - `True`: Yes, limit the CPU usage; limits to 1 CPU.
33
+ - Integer `>= 1`: Limits usage to the specified number of CPUs.
34
+ - Decimal value (`float`) between 0 and 1: Fraction of total CPUs to use.
35
+ - Decimal value (`float`) between -1 and 0: Fraction of CPUs to *not* use.
36
+ - Integer `<= -1`: Subtract the absolute value from total CPUs.
37
+
38
+ N.B.: You probably don't want to divide the computation into tasks.
39
+ 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.
40
+ """
41
+ stateUniversal: computationState = outfitCountFolds(listDimensions, computationDivisions=computationDivisions, CPUlimit=CPUlimit, **keywordArguments)
42
+
43
+ pathFilenameFoldsTotal = None
44
+ if pathLikeWriteFoldsTotal is not None:
45
+ pathFilenameFoldsTotal = getPathFilenameFoldsTotal(stateUniversal['mapShape'], pathLikeWriteFoldsTotal)
46
+
47
+ dispatcher = getDispatcherCallable()
48
+ dispatcher(**stateUniversal)
49
+
50
+ foldsTotal = int(stateUniversal['foldGroups'][0:-1].sum() * stateUniversal['foldGroups'][-1])
51
+
52
+ if pathFilenameFoldsTotal is not None:
53
+ saveFoldsTotal(pathFilenameFoldsTotal, foldsTotal)
54
+
55
+ return foldsTotal
mapFolding/beDRY.py ADDED
@@ -0,0 +1,376 @@
1
+ """A relatively stable API for oft-needed functionality."""
2
+ from mapFolding import (
3
+ computationState,
4
+ getPathJobRootDEFAULT,
5
+ hackSSOTdtype,
6
+ indexMy,
7
+ indexTrack,
8
+ setDatatypeElephino,
9
+ setDatatypeFoldsTotal,
10
+ setDatatypeLeavesTotal,
11
+ )
12
+ from numpy import integer
13
+ from numpy.typing import DTypeLike, NDArray
14
+ from typing import Any, List, Optional, Sequence, Tuple, Type, Union
15
+ from Z0Z_tools import defineConcurrencyLimit, intInnit, oopsieKwargsie
16
+ import numba
17
+ import numpy
18
+ import os
19
+ import pathlib
20
+ import sys
21
+
22
+ def getFilenameFoldsTotal(mapShape: Union[Sequence[int], numpy.ndarray[Tuple[int], numpy.dtype[integer[Any]]]]) -> str:
23
+ """Make a standardized filename for the computed value `foldsTotal`.
24
+
25
+ The filename takes into account
26
+ - the dimensions of the map, aka `mapShape`, aka `listDimensions`
27
+ - no spaces in the filename
28
+ - safe filesystem characters across platforms
29
+ - unique extension
30
+ - avoiding potential problems when Python is manipulating the filename, including
31
+ - treating the file stem as a valid Python identifier, such as
32
+ - not starting with a number
33
+ - not using reserved words
34
+ - no dashes or other special characters
35
+ - uh, I can't remember, but I found some frustrating edge limitations
36
+ - if 'p' is still the first character, I picked that because it was the original identifier for the map shape in Lunnan's code
37
+
38
+ Parameters:
39
+ mapShape: A sequence of integers representing the dimensions of the map (e.g., [3, 2] for a 3x2 map)
40
+
41
+ Returns:
42
+ filenameFoldsTotal: A filename string in format 'pNxM.foldsTotal' where N,M are sorted dimensions
43
+ """
44
+ return 'p' + 'x'.join(str(dim) for dim in sorted(mapShape)) + '.foldsTotal'
45
+
46
+ def getLeavesTotal(listDimensions: Sequence[int]) -> int:
47
+ """
48
+ How many leaves are in the map.
49
+
50
+ Parameters:
51
+ listDimensions: A list of integers representing dimensions.
52
+
53
+ Returns:
54
+ productDimensions: The product of all positive integer dimensions.
55
+ """
56
+ listNonNegative = parseDimensions(listDimensions, 'listDimensions')
57
+ listPositive = [dimension for dimension in listNonNegative if dimension > 0]
58
+
59
+ if not listPositive:
60
+ return 0
61
+ else:
62
+ productDimensions = 1
63
+ for dimension in listPositive:
64
+ if dimension > sys.maxsize // productDimensions:
65
+ raise OverflowError(f"I received {dimension=} in {listDimensions=}, but the product of the dimensions exceeds the maximum size of an integer on this system.")
66
+ productDimensions *= dimension
67
+
68
+ return productDimensions
69
+
70
+ def getPathFilenameFoldsTotal(mapShape: Union[Sequence[int], numpy.ndarray[Tuple[int], numpy.dtype[integer[Any]]]], pathLikeWriteFoldsTotal: Optional[Union[str, os.PathLike[str]]] = None) -> pathlib.Path:
71
+ """Get path for folds total file.
72
+
73
+ This function determines the file path for storing fold totals. If a path is provided,
74
+ it will use that path. If the path is a directory, it will append a default filename.
75
+ The function ensures the parent directory exists by creating it if necessary.
76
+
77
+ Parameters:
78
+ mapShape (Sequence[int]): List of dimensions for the map folding problem.
79
+ pathLikeWriteFoldsTotal (Union[str, os.PathLike[str]], optional): Path where to save
80
+ the folds total. Can be a file path or directory path. If None, uses default path.
81
+ Defaults to None.
82
+
83
+ Returns:
84
+ pathlib.Path: Complete path to the folds total file.
85
+ """
86
+ pathFilenameFoldsTotal = pathlib.Path(pathLikeWriteFoldsTotal) if pathLikeWriteFoldsTotal is not None else getPathJobRootDEFAULT()
87
+ if pathFilenameFoldsTotal.is_dir():
88
+ filenameFoldsTotalDEFAULT = getFilenameFoldsTotal(mapShape)
89
+ pathFilenameFoldsTotal = pathFilenameFoldsTotal / filenameFoldsTotalDEFAULT
90
+ elif pathlib.Path(pathLikeWriteFoldsTotal).is_absolute(): # type: ignore
91
+ pathFilenameFoldsTotal = pathlib.Path(pathLikeWriteFoldsTotal) # type: ignore
92
+ else:
93
+ pathFilenameFoldsTotal = pathlib.Path(getPathJobRootDEFAULT(), pathLikeWriteFoldsTotal) # type: ignore
94
+
95
+ pathFilenameFoldsTotal.parent.mkdir(parents=True, exist_ok=True)
96
+ return pathFilenameFoldsTotal
97
+
98
+ def getTaskDivisions(computationDivisions: Optional[Union[int, str]], concurrencyLimit: int, CPUlimit: Optional[Union[bool, float, int]], listDimensions: Sequence[int]) -> int:
99
+ """
100
+ Determines whether or how to divide the computation into tasks.
101
+
102
+ Parameters
103
+ ----------
104
+ computationDivisions (None):
105
+ Specifies how to divide computations:
106
+ - None: no division of the computation into tasks; sets task divisions to 0
107
+ - int: direct set the number of task divisions; cannot exceed the map's total leaves
108
+ - "maximum": divides into `leavesTotal`-many `taskDivisions`
109
+ - "cpu": limits the divisions to the number of available CPUs, i.e. `concurrencyLimit`
110
+ concurrencyLimit:
111
+ Maximum number of concurrent tasks allowed
112
+ CPUlimit: for error reporting
113
+ listDimensions: for error reporting
114
+
115
+ Returns
116
+ -------
117
+ taskDivisions:
118
+
119
+ Raises
120
+ ------
121
+ ValueError
122
+ If computationDivisions is an unsupported type or if resulting task divisions exceed total leaves
123
+
124
+ Notes
125
+ -----
126
+ Task divisions cannot exceed total leaves to prevent duplicate counting of folds.
127
+ """
128
+ taskDivisions = 0
129
+ leavesTotal = getLeavesTotal(listDimensions)
130
+ if not computationDivisions:
131
+ pass
132
+ elif isinstance(computationDivisions, int):
133
+ taskDivisions = computationDivisions
134
+ elif isinstance(computationDivisions, str):
135
+ computationDivisions = computationDivisions.lower()
136
+ if computationDivisions == "maximum":
137
+ taskDivisions = leavesTotal
138
+ elif computationDivisions == "cpu":
139
+ taskDivisions = min(concurrencyLimit, leavesTotal)
140
+ else:
141
+ raise ValueError(f"I received {computationDivisions} for the parameter, `computationDivisions`, but the so-called programmer didn't implement code for that.")
142
+
143
+ if taskDivisions > leavesTotal:
144
+ 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.\n\nFor those parameters, I received {computationDivisions=}, {CPUlimit=}, and {listDimensions=}.\n\nPotential solutions: get a different hobby or set `computationDivisions` to a different value.")
145
+
146
+ return taskDivisions
147
+
148
+ def makeConnectionGraph(listDimensions: Sequence[int], **keywordArguments: Optional[Type]) -> numpy.ndarray[Tuple[int, int, int], numpy.dtype[integer[Any]]]:
149
+ """
150
+ Constructs a multi-dimensional connection graph representing the connections between the leaves of a map with the given dimensions.
151
+ Also called a Cartesian product decomposition or dimensional product mapping.
152
+
153
+ Parameters
154
+ listDimensions: A sequence of integers representing the dimensions of the map.
155
+ **keywordArguments: Datatype management.
156
+
157
+ Returns
158
+ connectionGraph: A 3D numpy array with shape of (dimensionsTotal, leavesTotal + 1, leavesTotal + 1).
159
+ """
160
+ if keywordArguments.get('datatype', None):
161
+ setDatatypeLeavesTotal(keywordArguments['datatype']) # type: ignore
162
+ datatype = hackSSOTdtype('connectionGraph')
163
+ mapShape = validateListDimensions(listDimensions)
164
+ leavesTotal = getLeavesTotal(mapShape)
165
+ arrayDimensions = numpy.array(mapShape, dtype=datatype)
166
+ dimensionsTotal = len(arrayDimensions)
167
+
168
+ cumulativeProduct = numpy.multiply.accumulate([1] + mapShape, dtype=datatype)
169
+ coordinateSystem = numpy.zeros((dimensionsTotal, leavesTotal + 1), dtype=datatype)
170
+ for indexDimension in range(dimensionsTotal):
171
+ for leaf1ndex in range(1, leavesTotal + 1):
172
+ coordinateSystem[indexDimension, leaf1ndex] = ( ((leaf1ndex - 1) // cumulativeProduct[indexDimension]) % arrayDimensions[indexDimension] + 1 )
173
+
174
+ connectionGraph = numpy.zeros((dimensionsTotal, leavesTotal + 1, leavesTotal + 1), dtype=datatype)
175
+ for indexDimension in range(dimensionsTotal):
176
+ for activeLeaf1ndex in range(1, leavesTotal + 1):
177
+ for connectee1ndex in range(1, activeLeaf1ndex + 1):
178
+ isFirstCoord = coordinateSystem[indexDimension, connectee1ndex] == 1
179
+ isLastCoord = coordinateSystem[indexDimension, connectee1ndex] == arrayDimensions[indexDimension]
180
+ exceedsActive = connectee1ndex + cumulativeProduct[indexDimension] > activeLeaf1ndex
181
+ isEvenParity = (coordinateSystem[indexDimension, activeLeaf1ndex] & 1) == (coordinateSystem[indexDimension, connectee1ndex] & 1)
182
+
183
+ if (isEvenParity and isFirstCoord) or (not isEvenParity and (isLastCoord or exceedsActive)):
184
+ connectionGraph[indexDimension, activeLeaf1ndex, connectee1ndex] = connectee1ndex
185
+ elif isEvenParity and not isFirstCoord:
186
+ connectionGraph[indexDimension, activeLeaf1ndex, connectee1ndex] = connectee1ndex - cumulativeProduct[indexDimension]
187
+ elif not isEvenParity and not (isLastCoord or exceedsActive):
188
+ connectionGraph[indexDimension, activeLeaf1ndex, connectee1ndex] = connectee1ndex + cumulativeProduct[indexDimension]
189
+
190
+ return connectionGraph
191
+
192
+ def makeDataContainer(shape: Union[int, Tuple[int, ...]], datatype: Optional[DTypeLike] = None) -> NDArray[integer[Any]]:
193
+ """Create a zeroed-out `numpy.ndarray` with the given shape and datatype.
194
+
195
+ Parameters:
196
+ shape (Union[int, Tuple[int, ...]]): The shape of the array. Can be an integer for 1D arrays
197
+ or a tuple of integers for multi-dimensional arrays.
198
+ datatype (Optional[DTypeLike], optional): The desired data type for the array.
199
+ If None, defaults to dtypeLargeDEFAULT. Defaults to None.
200
+
201
+ Returns:
202
+ numpy.ndarray: A new array of given shape and type, filled with zeros.
203
+ """
204
+ if datatype is None:
205
+ datatype = hackSSOTdtype('dtypeFoldsTotal')
206
+ return numpy.zeros(shape, dtype=datatype)
207
+
208
+ def outfitCountFolds(listDimensions: Sequence[int]
209
+ , computationDivisions: Optional[Union[int, str]] = None
210
+ , CPUlimit: Optional[Union[bool, float, int]] = None
211
+ , **keywordArguments: Optional[Union[str, bool]]) -> computationState:
212
+ """
213
+ Initializes and configures the computation state for map folding computations.
214
+
215
+ Parameters
216
+ ----------
217
+ listDimensions:
218
+ The dimensions of the map to be folded
219
+ computationDivisions (None):
220
+ Specifies how to divide computations:
221
+ - None: no division of the computation into tasks; sets task divisions to 0
222
+ - int: direct set the number of task divisions; cannot exceed the map's total leaves
223
+ - "maximum": divides into `leavesTotal`-many `taskDivisions`
224
+ - "cpu": limits the divisions to the number of available CPUs, i.e. `concurrencyLimit`
225
+ CPUlimit (None):
226
+ Whether and how to limit the CPU usage. See notes for details.
227
+ **keywordArguments:
228
+ Datatype management.
229
+
230
+ Returns
231
+ -------
232
+ computationState
233
+ An initialized computation state containing:
234
+ - connectionGraph: Graph representing connections in the map
235
+ - foldsSubTotals: Array tracking total folds
236
+ - mapShape: Validated and sorted dimensions of the map
237
+ - my: Array for internal state tracking
238
+ - gapsWhere: Array tracking gap positions
239
+ - the: Static settings and metadata
240
+ - track: Array for tracking computation progress
241
+
242
+ Limits on CPU usage `CPUlimit`:
243
+ - `False`, `None`, or `0`: No limits on CPU usage; uses all available CPUs. All other values will potentially limit CPU usage.
244
+ - `True`: Yes, limit the CPU usage; limits to 1 CPU.
245
+ - Integer `>= 1`: Limits usage to the specified number of CPUs.
246
+ - Decimal value (`float`) between 0 and 1: Fraction of total CPUs to use.
247
+ - Decimal value (`float`) between -1 and 0: Fraction of CPUs to *not* use.
248
+ - Integer `<= -1`: Subtract the absolute value from total CPUs.
249
+ """
250
+ kwourGrapes = keywordArguments.get('sourGrapes', False)
251
+ kwatatype = keywordArguments.get('datatypeElephino', None)
252
+ if kwatatype: setDatatypeElephino(kwatatype, sourGrapes=kwourGrapes) # type: ignore
253
+ kwatatype = keywordArguments.get('datatypeFoldsTotal', None)
254
+ if kwatatype: setDatatypeFoldsTotal(kwatatype, sourGrapes=kwourGrapes) # type: ignore
255
+ kwatatype = keywordArguments.get('datatypeLeavesTotal', None)
256
+ if kwatatype: setDatatypeLeavesTotal(kwatatype, sourGrapes=kwourGrapes) # type: ignore
257
+
258
+ my = makeDataContainer(len(indexMy), hackSSOTdtype('my'))
259
+
260
+ mapShape = tuple(sorted(validateListDimensions(listDimensions)))
261
+ concurrencyLimit = setCPUlimit(CPUlimit)
262
+ my[indexMy.taskDivisions] = getTaskDivisions(computationDivisions, concurrencyLimit, CPUlimit, mapShape)
263
+
264
+ foldGroups = makeDataContainer(max(my[indexMy.taskDivisions] + 1, 2), hackSSOTdtype('foldGroups'))
265
+ leavesTotal = getLeavesTotal(mapShape)
266
+ foldGroups[-1] = leavesTotal
267
+
268
+ my[indexMy.dimensionsTotal] = len(mapShape)
269
+ my[indexMy.leaf1ndex] = 1
270
+ stateInitialized = computationState(
271
+ connectionGraph = makeConnectionGraph(mapShape, datatype=hackSSOTdtype('connectionGraph')),
272
+ foldGroups = foldGroups,
273
+ mapShape = numpy.array(mapShape, dtype=hackSSOTdtype('mapShape')),
274
+ my = my,
275
+ gapsWhere = makeDataContainer(int(leavesTotal) * int(leavesTotal) + 1, hackSSOTdtype('gapsWhere')),
276
+ track = makeDataContainer((len(indexTrack), leavesTotal + 1), hackSSOTdtype('track')),
277
+ )
278
+
279
+ return stateInitialized
280
+
281
+ def parseDimensions(dimensions: Sequence[int], parameterName: str = 'listDimensions') -> List[int]:
282
+ """
283
+ Parse and validate dimensions are non-negative integers.
284
+
285
+ Parameters:
286
+ dimensions: Sequence of integers representing dimensions
287
+ parameterName ('listDimensions'): Name of the parameter for error messages. Defaults to 'listDimensions'
288
+ Returns:
289
+ listNonNegative: List of validated non-negative integers
290
+ Raises:
291
+ ValueError: If any dimension is negative or if the list is empty
292
+ TypeError: If any element cannot be converted to integer (raised by intInnit)
293
+ """
294
+ listValidated = intInnit(dimensions, parameterName)
295
+ listNonNegative = []
296
+ for dimension in listValidated:
297
+ if dimension < 0:
298
+ raise ValueError(f"Dimension {dimension} must be non-negative")
299
+ listNonNegative.append(dimension)
300
+
301
+ return listNonNegative
302
+
303
+ def saveFoldsTotal(pathFilename: Union[str, os.PathLike[str]], foldsTotal: int) -> None:
304
+ """
305
+ Save foldsTotal with multiple fallback mechanisms.
306
+
307
+ Parameters:
308
+ pathFilename: Target save location
309
+ foldsTotal: Critical computed value to save
310
+ """
311
+ try:
312
+ pathFilenameFoldsTotal = pathlib.Path(pathFilename)
313
+ pathFilenameFoldsTotal.parent.mkdir(parents=True, exist_ok=True)
314
+ pathFilenameFoldsTotal.write_text(str(foldsTotal))
315
+ except Exception as ERRORmessage:
316
+ try:
317
+ print(f"\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n\n{foldsTotal=}\n\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n")
318
+ print(ERRORmessage)
319
+ print(f"\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n\n{foldsTotal=}\n\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n")
320
+ randomnessPlanB = (int(str(foldsTotal).strip()[-1]) + 1) * ['YO_']
321
+ filenameInfixUnique = ''.join(randomnessPlanB)
322
+ pathFilenamePlanB = os.path.join(os.getcwd(), 'foldsTotal' + filenameInfixUnique + '.txt')
323
+ writeStreamFallback = open(pathFilenamePlanB, 'w')
324
+ writeStreamFallback.write(str(foldsTotal))
325
+ writeStreamFallback.close()
326
+ print(str(pathFilenamePlanB))
327
+ except Exception:
328
+ print(foldsTotal)
329
+
330
+ def setCPUlimit(CPUlimit: Optional[Any]) -> int:
331
+ """Sets CPU limit for Numba concurrent operations. Note that it can only affect Numba-jitted functions that have not yet been imported.
332
+
333
+ Parameters:
334
+ CPUlimit: whether and how to limit the CPU usage. See notes for details.
335
+ Returns:
336
+ concurrencyLimit: The actual concurrency limit that was set
337
+ Raises:
338
+ TypeError: If CPUlimit is not of the expected types
339
+
340
+ Limits on CPU usage `CPUlimit`:
341
+ - `False`, `None`, or `0`: No limits on CPU usage; uses all available CPUs. All other values will potentially limit CPU usage.
342
+ - `True`: Yes, limit the CPU usage; limits to 1 CPU.
343
+ - Integer `>= 1`: Limits usage to the specified number of CPUs.
344
+ - Decimal value (`float`) between 0 and 1: Fraction of total CPUs to use.
345
+ - Decimal value (`float`) between -1 and 0: Fraction of CPUs to *not* use.
346
+ - Integer `<= -1`: Subtract the absolute value from total CPUs.
347
+ """
348
+ if not (CPUlimit is None or isinstance(CPUlimit, (bool, int, float))):
349
+ CPUlimit = oopsieKwargsie(CPUlimit)
350
+
351
+ concurrencyLimit = int(defineConcurrencyLimit(CPUlimit))
352
+ numba.set_num_threads(concurrencyLimit)
353
+
354
+ return concurrencyLimit
355
+
356
+ def validateListDimensions(listDimensions: Sequence[int]) -> List[int]:
357
+ """
358
+ Validates and sorts a sequence of at least two positive dimensions.
359
+
360
+ Parameters:
361
+ listDimensions: A sequence of integer dimensions to be validated.
362
+
363
+ Returns:
364
+ dimensionsValidSorted: A list, with at least two elements, of only positive integers.
365
+
366
+ Raises:
367
+ ValueError: If the input listDimensions is None.
368
+ NotImplementedError: If the resulting list of positive dimensions has fewer than two elements.
369
+ """
370
+ if not listDimensions:
371
+ raise ValueError("listDimensions is a required parameter.")
372
+ listNonNegative = parseDimensions(listDimensions, 'listDimensions')
373
+ dimensionsValid = [dimension for dimension in listNonNegative if dimension > 0]
374
+ if len(dimensionsValid) < 2:
375
+ 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/.")
376
+ return sorted(dimensionsValid)