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