mapFolding 0.2.2__py3-none-any.whl → 0.2.4__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.
@@ -0,0 +1,376 @@
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
+ dtypeDefault = 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
+ if isinstance(computationDivisions, int):
271
+ taskDivisions = computationDivisions
272
+ elif isinstance(computationDivisions, str):
273
+ computationDivisions = computationDivisions.lower()
274
+ if computationDivisions == "maximum":
275
+ taskDivisions = leavesTotal
276
+ elif computationDivisions == "cpu":
277
+ taskDivisions = min(concurrencyLimit, leavesTotal)
278
+ else:
279
+ raise ValueError("Not my problem.")
280
+
281
+ if taskDivisions > leavesTotal:
282
+ raise ValueError("What are you doing?")
283
+
284
+ return taskDivisions
285
+
286
+ def makeConnectionGraph(listDimensions: Sequence[int], **keywordArguments: Optional[Type]) -> NDArray[integer[Any]]:
287
+ datatype = keywordArguments.get('datatype', dtypeDefault)
288
+ mapShape = validateListDimensions(listDimensions)
289
+ leavesTotal = getLeavesTotal(mapShape)
290
+ arrayDimensions = numpy.array(mapShape, dtype=datatype)
291
+ dimensionsTotal = len(arrayDimensions)
292
+
293
+ cumulativeProduct = numpy.multiply.accumulate([1] + mapShape, dtype=datatype)
294
+ coordinateSystem = numpy.zeros((dimensionsTotal + 1, leavesTotal + 1), dtype=datatype)
295
+ for dimension1ndex in range(1, dimensionsTotal + 1):
296
+ for leaf1ndex in range(1, leavesTotal + 1):
297
+ coordinateSystem[dimension1ndex, leaf1ndex] = ( ((leaf1ndex - 1) // cumulativeProduct[dimension1ndex - 1]) % arrayDimensions[dimension1ndex - 1] + 1 )
298
+
299
+ connectionGraph = numpy.zeros((dimensionsTotal + 1, leavesTotal + 1, leavesTotal + 1), dtype=datatype)
300
+ for dimension1ndex in range(1, dimensionsTotal + 1):
301
+ for activeLeaf1ndex in range(1, leavesTotal + 1):
302
+ for connectee1ndex in range(1, activeLeaf1ndex + 1):
303
+ isFirstCoord = coordinateSystem[dimension1ndex, connectee1ndex] == 1
304
+ isLastCoord = coordinateSystem[dimension1ndex, connectee1ndex] == arrayDimensions[dimension1ndex - 1]
305
+ exceedsActive = connectee1ndex + cumulativeProduct[dimension1ndex - 1] > activeLeaf1ndex
306
+ isEvenParity = (coordinateSystem[dimension1ndex, activeLeaf1ndex] & 1) == (coordinateSystem[dimension1ndex, connectee1ndex] & 1)
307
+
308
+ if (isEvenParity and isFirstCoord) or (not isEvenParity and (isLastCoord or exceedsActive)):
309
+ connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex
310
+ elif isEvenParity and not isFirstCoord:
311
+ connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex - cumulativeProduct[dimension1ndex - 1]
312
+ elif not isEvenParity and not (isLastCoord or exceedsActive):
313
+ connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex + cumulativeProduct[dimension1ndex - 1]
314
+ else:
315
+ connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex
316
+ return connectionGraph
317
+
318
+ def makeDataContainer(shape, datatype: Optional[Type] = None):
319
+ if datatype is None:
320
+ datatype = dtypeDefault
321
+ return numpy.zeros(shape, dtype=datatype)
322
+
323
+ def outfitFoldings(listDimensions: Sequence[int], computationDivisions: Optional[Union[int, str]] = None, CPUlimit: Optional[Union[bool, float, int]] = None, **keywordArguments: Optional[Type]) -> computationState:
324
+ datatypeDefault = keywordArguments.get('datatypeDefault', dtypeDefault)
325
+ datatypeLarge = keywordArguments.get('datatypeLarge', dtypeLarge)
326
+
327
+ the = makeDataContainer(len(indexThe), datatypeDefault)
328
+
329
+ mapShape = tuple(sorted(validateListDimensions(listDimensions)))
330
+ the[indexThe.leavesTotal] = getLeavesTotal(mapShape)
331
+ the[indexThe.dimensionsTotal] = len(mapShape)
332
+ concurrencyLimit = setCPUlimit(CPUlimit)
333
+ the[indexThe.taskDivisions] = getTaskDivisions(computationDivisions, concurrencyLimit, CPUlimit, listDimensions)
334
+
335
+ stateInitialized = computationState(
336
+ connectionGraph = makeConnectionGraph(mapShape, datatype=datatypeDefault),
337
+ foldsSubTotals = makeDataContainer(the[indexThe.leavesTotal], datatypeLarge),
338
+ mapShape = mapShape,
339
+ my = makeDataContainer(len(indexMy), datatypeLarge),
340
+ gapsWhere = makeDataContainer(int(the[indexThe.leavesTotal]) * int(the[indexThe.leavesTotal]) + 1, datatypeDefault),
341
+ the = the,
342
+ track = makeDataContainer((len(indexTrack), the[indexThe.leavesTotal] + 1), datatypeLarge)
343
+ )
344
+
345
+ stateInitialized['my'][indexMy.leaf1ndex] = 1
346
+ return stateInitialized
347
+
348
+ def parseDimensions(dimensions: Sequence[int], parameterName: str = 'unnamed parameter') -> List[int]:
349
+ # listValidated = intInnit(dimensions, parameterName)
350
+ listNOTValidated = dimensions if isinstance(dimensions, (list, tuple)) else list(dimensions)
351
+ listNonNegative = []
352
+ for dimension in listNOTValidated:
353
+ if dimension < 0:
354
+ raise ValueError(f"Dimension {dimension} must be non-negative")
355
+ listNonNegative.append(dimension)
356
+ if not listNonNegative:
357
+ raise ValueError("At least one dimension must be non-negative")
358
+ return listNonNegative
359
+
360
+ def setCPUlimit(CPUlimit: Union[bool, float, int, None]) -> int:
361
+ # if not (CPUlimit is None or isinstance(CPUlimit, (bool, int, float))):
362
+ # CPUlimit = oopsieKwargsie(CPUlimit)
363
+ # concurrencyLimit = defineConcurrencyLimit(CPUlimit)
364
+ # numba.set_num_threads(concurrencyLimit)
365
+ concurrencyLimitHARDCODED = 1
366
+ concurrencyLimit = concurrencyLimitHARDCODED
367
+ return concurrencyLimit
368
+
369
+ def validateListDimensions(listDimensions: Sequence[int]) -> List[int]:
370
+ if not listDimensions:
371
+ raise ValueError(f"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)
mapFolding/startHere.py CHANGED
@@ -1,4 +1,4 @@
1
- from mapFolding import outfitFoldings
1
+ from mapFolding import outfitCountFolds, getFilenameFoldsTotal
2
2
  from typing import Optional, Sequence, Type, Union
3
3
  import os
4
4
  import pathlib
@@ -15,7 +15,7 @@ def countFolds(listDimensions: Sequence[int], writeFoldsTotal: Optional[Union[st
15
15
  CPUlimit (None): This is only relevant if there are `computationDivisions`: whether and how to limit the CPU usage. See notes for details.
16
16
  **keywordArguments: Additional arguments including `dtypeDefault` and `dtypeLarge` for data type specifications.
17
17
  Returns:
18
- foldsTotal: Total number of distinct ways to fold a map of the given dimensions.
18
+ foldsSubTotals: Total number of distinct ways to fold a map of the given dimensions.
19
19
 
20
20
  Computation divisions:
21
21
  - None: no division of the computation into tasks; sets task divisions to 0
@@ -34,20 +34,20 @@ def countFolds(listDimensions: Sequence[int], writeFoldsTotal: Optional[Union[st
34
34
  N.B.: You probably don't want to divide the computation into tasks.
35
35
  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.
36
36
  """
37
- stateUniversal = outfitFoldings(listDimensions, computationDivisions=computationDivisions, CPUlimit=CPUlimit, **keywordArguments)
37
+ stateUniversal = outfitCountFolds(listDimensions, computationDivisions=computationDivisions, CPUlimit=CPUlimit, **keywordArguments)
38
38
 
39
39
  pathFilenameFoldsTotal = None
40
40
  if writeFoldsTotal is not None:
41
41
  pathFilenameFoldsTotal = pathlib.Path(writeFoldsTotal)
42
42
  if pathFilenameFoldsTotal.is_dir():
43
- filenameFoldsTotalDEFAULT = str(sorted(stateUniversal['mapShape'])).replace(' ', '') + '.foldsTotal'
43
+ filenameFoldsTotalDEFAULT = getFilenameFoldsTotal(stateUniversal['mapShape'])
44
44
  pathFilenameFoldsTotal = pathFilenameFoldsTotal / filenameFoldsTotalDEFAULT
45
45
  pathFilenameFoldsTotal.parent.mkdir(parents=True, exist_ok=True)
46
46
 
47
- # NOTE Don't import a module with a numba.jit function until you want the function to compile and to freeze all settings for that function.
48
47
  from mapFolding.babbage import _countFolds
49
- foldsTotal = _countFolds(**stateUniversal)
50
- # foldsTotal = benchmarkSherpa(**stateUniversal)
48
+ _countFolds(**stateUniversal)
49
+
50
+ foldsTotal = stateUniversal['foldsSubTotals'].sum().item()
51
51
 
52
52
  if pathFilenameFoldsTotal is not None:
53
53
  try:
@@ -57,12 +57,3 @@ def countFolds(listDimensions: Sequence[int], writeFoldsTotal: Optional[Union[st
57
57
  print(f"\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n\n{foldsTotal=}\n\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal")
58
58
 
59
59
  return foldsTotal
60
-
61
- # from numpy import integer
62
- # from numpy.typing import NDArray
63
- # from typing import Any, Tuple
64
- # from mapFolding.benchmarks.benchmarking import recordBenchmarks
65
- # @recordBenchmarks()
66
- # def benchmarkSherpa(connectionGraph: NDArray[integer[Any]], foldsTotal: NDArray[integer[Any]], mapShape: Tuple[int, ...], my: NDArray[integer[Any]], gapsWhere: NDArray[integer[Any]], the: NDArray[integer[Any]], track: NDArray[integer[Any]]):
67
- # from mapFolding.babbage import _countFolds
68
- # return _countFolds(connectionGraph, foldsTotal, mapShape, my, gapsWhere, the, track)
mapFolding/theSSOT.py CHANGED
@@ -5,9 +5,17 @@ import numpy.typing
5
5
  import pathlib
6
6
  import sys
7
7
 
8
- dtypeLarge = numpy.int64
9
- dtypeDefault = dtypeLarge
10
- dtypeSmall = dtypeDefault
8
+ datatypeModule = 'numpy'
9
+
10
+ datatypeLarge = 'int64'
11
+ datatypeDefault = datatypeLarge
12
+ datatypeSmall = datatypeDefault
13
+
14
+ make_dtype = lambda _datatype: eval(f"{datatypeModule}.{_datatype}")
15
+
16
+ dtypeLarge = make_dtype(datatypeLarge)
17
+ dtypeDefault = make_dtype(datatypeDefault)
18
+ dtypeSmall = make_dtype(datatypeSmall)
11
19
 
12
20
  try:
13
21
  _pathModule = pathlib.Path(__file__).parent
@@ -15,7 +23,7 @@ except NameError:
15
23
  _pathModule = pathlib.Path.cwd()
16
24
 
17
25
  pathJobDEFAULT = _pathModule / "jobs"
18
- """filenameFoldsTotal = str(sorted(mapShape)).replace(' ', '') + '.foldsTotal'"""
26
+
19
27
  if 'google.colab' in sys.modules:
20
28
  pathJobDEFAULT = pathlib.Path("/content/drive/MyDrive") / "jobs"
21
29
 
@@ -59,9 +67,9 @@ class indexTrack(EnumIndices):
59
67
 
60
68
  class computationState(TypedDict):
61
69
  connectionGraph: numpy.typing.NDArray[numpy.integer[Any]]
62
- foldsTotal: numpy.ndarray[numpy.int64, numpy.dtype[numpy.int64]]
70
+ foldsSubTotals: numpy.typing.NDArray[numpy.integer[Any]]
71
+ gapsWhere: numpy.typing.NDArray[numpy.integer[Any]]
63
72
  mapShape: Tuple[int, ...]
64
73
  my: numpy.typing.NDArray[numpy.integer[Any]]
65
- gapsWhere: numpy.typing.NDArray[numpy.integer[Any]]
66
74
  the: numpy.typing.NDArray[numpy.integer[Any]]
67
75
  track: numpy.typing.NDArray[numpy.integer[Any]]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: mapFolding
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: Algorithm(s) for counting distinct ways to fold a map (or a strip of stamps)
5
5
  Author-email: Hunter Hogan <HunterHogan@pm.me>
6
6
  Project-URL: homepage, https://github.com/hunterhogan/mapFolding
@@ -22,10 +22,12 @@ Requires-Dist: pytest; extra == "testing"
22
22
  Requires-Dist: pytest-cov; extra == "testing"
23
23
  Requires-Dist: pytest-env; extra == "testing"
24
24
  Requires-Dist: pytest-xdist; extra == "testing"
25
+ Requires-Dist: pytest-order; extra == "testing"
26
+ Requires-Dist: pytest-dependency; extra == "testing"
25
27
 
26
28
  # Algorithm(s) for counting distinct ways to fold a map (or a strip of stamps)
27
29
 
28
- `mapFolding.countFolds()` will accept arbitrary values for the map's dimensions.
30
+ The function `mapFolding.countFolds()` counts distinct ways to fold maps and strips of stamps. The function accepts two or more dimensions:
29
31
 
30
32
  ```python
31
33
  from mapFolding import countFolds
@@ -34,12 +36,12 @@ foldsTotal = countFolds( [2,10] )
34
36
 
35
37
  The directory [mapFolding/reference](https://github.com/hunterhogan/mapFolding/blob/main/mapFolding/reference) has
36
38
 
37
- - a verbatim transcription of the "procedure" published in _The Computer Journal_,
39
+ - a verbatim transcription of Lunnon's "procedure" published in 1971 by _The Computer Journal_,
38
40
  - multiple referential versions of the procedure with explanatory comments including
39
41
  - [hunterNumba.py](https://github.com/hunterhogan/mapFolding/blob/main/mapFolding/reference), a one-size-fits-all, self-contained, reasonably fast, contemporary algorithm that is nevertheless infected by _noobaceae ignorancium_, and
40
42
  - miscellaneous notes.
41
43
 
42
- [![Python Tests](https://github.com/hunterhogan/mapFolding/actions/workflows/unittests.yml/badge.svg)](https://github.com/hunterhogan/mapFolding/actions/workflows/unittests.yml)
44
+ [![Python Tests](https://github.com/hunterhogan/mapFolding/actions/workflows/unittests.yml/badge.svg)](https://github.com/hunterhogan/mapFolding/actions/workflows/unittests.yml) [![pip install mapFolding](https://img.shields.io/badge/pip%20install-mapFolding-gray.svg?colorB=3b434b)](https://pypi.org/project/mapFolding/) ![Static Badge](https://img.shields.io/badge/stinkin'%20badges-don't%20need-b98e5e) ![PyPI - Downloads](https://img.shields.io/pypi/dd/mapFolding) ![Static Badge](https://img.shields.io/badge/issues-I%20have%20them-brightgreen) ![GitHub repo size](https://img.shields.io/github/repo-size/hunterhogan/mapFolding)
43
45
 
44
46
  ## Simple, easy usage based on OEIS IDs
45
47
 
@@ -0,0 +1,35 @@
1
+ mapFolding/__init__.py,sha256=wnf2EzHR2unVha6-Y0gRoSPaE4PDdT4VngINa_dfT2E,337
2
+ mapFolding/babbage.py,sha256=51fO7lwcTsTvSMwzKW1G2nGslGoEQt19IgnqZi8znao,2222
3
+ mapFolding/beDRY.py,sha256=XawGabR1vhzOfdA46HSXmisA5EmxisTKdA3D98KDeac,13699
4
+ mapFolding/countInitialize.py,sha256=pIeH52OwDMfuHXT2T4BbPmMm6r7zJnGc-e0QVQCKyDc,1824
5
+ mapFolding/countParallel.py,sha256=1sLGIlMj_xZ4bFkG1srOPcDUCrSKc1q3x2QN_8l_sgY,2451
6
+ mapFolding/countSequential.py,sha256=QSXwK3o8YBcxNrir_wGMXgqp38hXYTJanYXFLxUPCPo,1993
7
+ mapFolding/importSelector.py,sha256=OY_LuUrLW5SFV6qM1tSgI2Rnfi5Bj3Fhdrkryo0WycE,392
8
+ mapFolding/inlineAfunction.py,sha256=KO2snTNSGX-4urRtTOYqAZBCsBCaMfr5bo6rNZR9MPA,5102
9
+ mapFolding/lovelace.py,sha256=iu7anbA_TacIAjc4EKkeBVxIJKAMdrYgvR4evzMZ1WY,15193
10
+ mapFolding/oeis.py,sha256=_-fLGc1ybZ2eFxoiBrSmojMexeg6ROxtrLaBF2BzMn4,12144
11
+ mapFolding/startHere.py,sha256=or7QhxgMls2hvP_I2eTBP5tffLrc3SMiE5Gz_Ik2aJY,4328
12
+ mapFolding/theSSOT.py,sha256=3Zty4rYWOqrwivuCaKA71R0HM4rjmvtkL_Bsn4ZhwFo,2318
13
+ mapFolding/JAX/lunnanJAX.py,sha256=xMZloN47q-MVfjdYOM1hi9qR4OnLq7qALmGLMraevQs,14819
14
+ mapFolding/JAX/taskJAX.py,sha256=yJNeH0rL6EhJ6ppnATHF0Zf81CDMC10bnPnimVxE1hc,20037
15
+ mapFolding/benchmarks/benchmarking.py,sha256=HD_0NSvuabblg94ftDre6LFnXShTe8MYj3hIodW-zV0,3076
16
+ mapFolding/reference/flattened.py,sha256=X9nvRzg7YDcpCtSDTL4YiidjshlX9rg2e6JVCY6i2u0,16547
17
+ mapFolding/reference/hunterNumba.py,sha256=0giUyqAFzP-XKcq3Kz8wIWCK0BVFhjABVJ1s-w4Jhu0,7109
18
+ mapFolding/reference/irvineJavaPort.py,sha256=Sj-63Z-OsGuDoEBXuxyjRrNmmyl0d7Yz_XuY7I47Oyg,4250
19
+ mapFolding/reference/lunnan.py,sha256=XEcql_gxvCCghb6Or3qwmPbn4IZUbZTaSmw_fUjRxZE,5037
20
+ mapFolding/reference/lunnanNumpy.py,sha256=HqDgSwTOZA-G0oophOEfc4zs25Mv4yw2aoF1v8miOLk,4653
21
+ mapFolding/reference/lunnanWhile.py,sha256=7NY2IKO5XBgol0aWWF_Fi-7oTL9pvu_z6lB0TF1uVHk,4063
22
+ mapFolding/reference/rotatedEntryPoint.py,sha256=z0QyDQtnMvXNj5ntWzzJUQUMFm1-xHGLVhtYzwmczUI,11530
23
+ mapFolding/reference/total_countPlus1vsPlusN.py,sha256=usenM8Yn_G1dqlPl7NKKkcnbohBZVZBXTQRm2S3_EDA,8106
24
+ tests/__init__.py,sha256=eg9smg-6VblOr0kisM40CpGnuDtU2JgEEWGDTFVOlW8,57
25
+ tests/conftest.py,sha256=AWB3m_jxMlkmOmGvk2ApJEk2ro5v8gmmJDcyLwN1oow,13761
26
+ tests/pythons_idiotic_namespace.py,sha256=oOLDBergQqqhGuRpsXUnFD-R_6AlJipNKYHw-kk_OKw,33
27
+ tests/test_oeis.py,sha256=vxnwO-cSR68htkyMh9QMVv-lvxBo6qlwPg1Rbx4JylY,7963
28
+ tests/test_other.py,sha256=amhsy7VWzpuW_slBOTFPhC7e4o4k6Yp4xweNK1VHZnc,11906
29
+ tests/test_tasks.py,sha256=Nwe4iuSjwGZvsw5CXCcic7tkBxgM5JX9mrGZMDYhAwE,1785
30
+ tests/test_temporary.py,sha256=4FIEc9KGRpNsgU_eh8mXG49PSPqo8WLeZEyFI4Dpy3U,1127
31
+ mapFolding-0.2.4.dist-info/METADATA,sha256=w1OgxNLylmuYfEKUsSIChm_8jLtjV63_OB04n8Btjm8,6543
32
+ mapFolding-0.2.4.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
33
+ mapFolding-0.2.4.dist-info/entry_points.txt,sha256=F3OUeZR1XDTpoH7k3wXuRb3KF_kXTTeYhu5AGK1SiOQ,146
34
+ mapFolding-0.2.4.dist-info/top_level.txt,sha256=1gP2vFaqPwHujGwb3UjtMlLEGN-943VSYFR7V4gDqW8,17
35
+ mapFolding-0.2.4.dist-info/RECORD,,
tests/__init__.py CHANGED
@@ -1 +1 @@
1
- from .conftest import makeDictionaryFoldsTotalKnown
1
+ from tests.conftest import makeDictionaryFoldsTotalKnown
tests/conftest.py CHANGED
@@ -14,10 +14,10 @@ from Z0Z_tools.pytest_parseParameters import makeTestSuiteConcurrencyLimit
14
14
  from Z0Z_tools.pytest_parseParameters import makeTestSuiteIntInnit
15
15
  from Z0Z_tools.pytest_parseParameters import makeTestSuiteOopsieKwargsie
16
16
  from mapFolding import countFolds, pathJobDEFAULT, indexMy, indexThe, indexTrack
17
- from mapFolding import defineConcurrencyLimit, intInnit, oopsieKwargsie
18
- from mapFolding import getLeavesTotal, parseDimensions, validateListDimensions
19
- from mapFolding import getTaskDivisions, makeConnectionGraph, outfitFoldings, setCPUlimit
20
- from mapFolding import oeisIDfor_n, getOEISids, clearOEIScache
17
+ from mapFolding import defineConcurrencyLimit, intInnit, oopsieKwargsie, outfitCountFolds
18
+ from mapFolding import oeisIDfor_n, getOEISids, clearOEIScache, getFilenameFoldsTotal
19
+ from mapFolding.beDRY import getLeavesTotal, parseDimensions, validateListDimensions
20
+ from mapFolding.beDRY import getTaskDivisions, makeConnectionGraph, setCPUlimit
21
21
  from mapFolding.beDRY import makeDataContainer
22
22
  from mapFolding.oeis import OEIS_for_n
23
23
  from mapFolding.oeis import _getFilenameOEISbFile
@@ -37,10 +37,11 @@ __all__ = [
37
37
  'countFolds',
38
38
  'defineConcurrencyLimit',
39
39
  'expectSystemExit',
40
+ 'getFilenameFoldsTotal',
40
41
  'getLeavesTotal',
41
42
  'getOEISids',
42
- 'indexThe',
43
43
  'getTaskDivisions',
44
+ 'indexThe',
44
45
  'intInnit',
45
46
  'makeConnectionGraph',
46
47
  'makeDataContainer',
@@ -50,7 +51,7 @@ __all__ = [
50
51
  'oeisIDfor_n',
51
52
  'oeisIDsImplemented',
52
53
  'oopsieKwargsie',
53
- 'outfitFoldings',
54
+ 'outfitCountFolds',
54
55
  'parseDimensions',
55
56
  'setCPUlimit',
56
57
  'settingsOEIS',
@@ -133,6 +134,14 @@ def setupTeardownTestData() -> Generator[None, None, None]:
133
134
  yield
134
135
  cleanupTempFileRegister()
135
136
 
137
+ @pytest.fixture(autouse=True)
138
+ def setupWarningsAsErrors():
139
+ """Convert all warnings to errors for all tests."""
140
+ import warnings
141
+ warnings.filterwarnings("error")
142
+ yield
143
+ warnings.resetwarnings()
144
+
136
145
  @pytest.fixture
137
146
  def pathTempTesting(request: pytest.FixtureRequest) -> pathlib.Path:
138
147
  """Create a unique temp directory for each test function."""
@@ -227,6 +236,22 @@ def oeisID_1random() -> str:
227
236
  """Return one random valid OEIS ID."""
228
237
  return random.choice(oeisIDsImplemented)
229
238
 
239
+ @pytest.fixture
240
+ def mockFoldingFunction():
241
+ """Creates a mock function that simulates _countFolds behavior."""
242
+ def make_mock(foldsValue: int, listDimensions: List[int]):
243
+ arraySize = getLeavesTotal(listDimensions)
244
+ # The array needs to sum to our target value
245
+ mock_array = makeDataContainer(arraySize)
246
+ mock_array[arraySize - 1] = foldsValue # Put entire value in last position
247
+
248
+ def mock_countfolds(**keywordArguments):
249
+ keywordArguments['foldsSubTotals'][:] = mock_array
250
+ return None
251
+
252
+ return mock_countfolds
253
+ return make_mock
254
+
230
255
  """
231
256
  Section: Standardized test structures"""
232
257
 
@@ -0,0 +1 @@
1
+ from mapFolding.theSSOT import *