mapFolding 0.5.0__py3-none-any.whl → 0.5.1__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 (39) hide show
  1. mapFolding/__init__.py +93 -58
  2. mapFolding/basecamp.py +5 -5
  3. mapFolding/beDRY.py +5 -5
  4. mapFolding/oeis.py +26 -25
  5. mapFolding/theSSOT.py +3 -15
  6. mapFolding/theSSOTdatatypes.py +10 -20
  7. {mapFolding-0.5.0.dist-info → mapFolding-0.5.1.dist-info}/METADATA +2 -1
  8. mapFolding-0.5.1.dist-info/RECORD +14 -0
  9. {mapFolding-0.5.0.dist-info → mapFolding-0.5.1.dist-info}/top_level.txt +0 -1
  10. mapFolding/reference/flattened.py +0 -377
  11. mapFolding/reference/hunterNumba.py +0 -132
  12. mapFolding/reference/irvineJavaPort.py +0 -120
  13. mapFolding/reference/jax.py +0 -208
  14. mapFolding/reference/lunnan.py +0 -153
  15. mapFolding/reference/lunnanNumpy.py +0 -123
  16. mapFolding/reference/lunnanWhile.py +0 -121
  17. mapFolding/reference/rotatedEntryPoint.py +0 -240
  18. mapFolding/reference/total_countPlus1vsPlusN.py +0 -211
  19. mapFolding/someAssemblyRequired/__init__.py +0 -5
  20. mapFolding/someAssemblyRequired/getLLVMforNoReason.py +0 -19
  21. mapFolding/someAssemblyRequired/makeJob.py +0 -56
  22. mapFolding/someAssemblyRequired/synthesizeModuleJAX.py +0 -27
  23. mapFolding/someAssemblyRequired/synthesizeNumba.py +0 -345
  24. mapFolding/someAssemblyRequired/synthesizeNumbaGeneralized.py +0 -397
  25. mapFolding/someAssemblyRequired/synthesizeNumbaJob.py +0 -155
  26. mapFolding/someAssemblyRequired/synthesizeNumbaModules.py +0 -123
  27. mapFolding/syntheticModules/numbaCount.py +0 -158
  28. mapFolding/syntheticModules/numba_doTheNeedful.py +0 -13
  29. mapFolding-0.5.0.dist-info/RECORD +0 -39
  30. tests/__init__.py +0 -1
  31. tests/conftest.py +0 -335
  32. tests/test_computations.py +0 -42
  33. tests/test_oeis.py +0 -128
  34. tests/test_other.py +0 -175
  35. tests/test_tasks.py +0 -40
  36. /mapFolding/{syntheticModules/__init__.py → py.typed} +0 -0
  37. {mapFolding-0.5.0.dist-info → mapFolding-0.5.1.dist-info}/LICENSE +0 -0
  38. {mapFolding-0.5.0.dist-info → mapFolding-0.5.1.dist-info}/WHEEL +0 -0
  39. {mapFolding-0.5.0.dist-info → mapFolding-0.5.1.dist-info}/entry_points.txt +0 -0
@@ -1,377 +0,0 @@
1
- """The algorithm flattened into semantic sections.
2
- This version is not maintained, so you may see differences from the current version."""
3
- from numpy import integer
4
- from numpy.typing import NDArray
5
- from typing import List, Any, Final, Optional, Union, Sequence, Tuple, Type, TypedDict
6
- import enum
7
- import numpy
8
- import sys
9
-
10
- def countFolds(listDimensions: Sequence[int], computationDivisions = None, CPUlimit: Optional[Union[int, float, bool]] = None):
11
- def doWhile():
12
-
13
- while activeLeafGreaterThan0Condition():
14
-
15
- if activeLeafIsTheFirstLeafCondition() or leafBelowSentinelIs1Condition():
16
-
17
- if activeLeafGreaterThanLeavesTotalCondition():
18
- foldsSubTotalsIncrement()
19
-
20
- else:
21
-
22
- findGapsInitializeVariables()
23
- while loopingTheDimensions():
24
-
25
- if dimensionsUnconstrainedCondition():
26
- dimensionsUnconstrainedIncrement()
27
-
28
- else:
29
-
30
- leafConnecteeInitialization()
31
- while loopingLeavesConnectedToActiveLeaf():
32
- if thereAreComputationDivisionsYouMightSkip():
33
- countGaps()
34
- leafConnecteeUpdate()
35
-
36
- dimension1ndexIncrement()
37
-
38
- if allDimensionsAreUnconstrained():
39
- insertUnconstrainedLeaf()
40
-
41
- indexMiniGapInitialization()
42
- while loopingToActiveGapCeiling():
43
- filterCommonGaps()
44
- indexMiniGapIncrement()
45
-
46
- while backtrackCondition():
47
- backtrack()
48
-
49
- if placeLeafCondition():
50
- placeLeaf()
51
-
52
- def activeGapIncrement():
53
- my[indexMy.gap1ndex] += 1
54
-
55
- def activeLeafGreaterThan0Condition():
56
- return my[indexMy.leaf1ndex] > 0
57
-
58
- def activeLeafGreaterThanLeavesTotalCondition():
59
- return my[indexMy.leaf1ndex] > the[indexThe.leavesTotal]
60
-
61
- def activeLeafIsTheFirstLeafCondition():
62
- return my[indexMy.leaf1ndex] <= 1
63
-
64
- def activeLeafNotEqualToTaskDivisionsCondition():
65
- return my[indexMy.leaf1ndex] != the[indexThe.taskDivisions]
66
-
67
- def allDimensionsAreUnconstrained():
68
- return my[indexMy.dimensionsUnconstrained] == the[indexThe.dimensionsTotal]
69
-
70
- def backtrack():
71
- my[indexMy.leaf1ndex] -= 1
72
- track[indexTrack.leafBelow, track[indexTrack.leafAbove, my[indexMy.leaf1ndex]]] = track[indexTrack.leafBelow, my[indexMy.leaf1ndex]]
73
- track[indexTrack.leafAbove, track[indexTrack.leafBelow, my[indexMy.leaf1ndex]]] = track[indexTrack.leafAbove, my[indexMy.leaf1ndex]]
74
-
75
- def backtrackCondition():
76
- return my[indexMy.leaf1ndex] > 0 and my[indexMy.gap1ndex] == track[indexTrack.gapRangeStart, my[indexMy.leaf1ndex] - 1]
77
-
78
- def computationDivisionsCondition():
79
- return the[indexThe.taskDivisions] == int(False)
80
-
81
- def countGaps():
82
- gapsWhere[my[indexMy.gap1ndexCeiling]] = my[indexMy.leafConnectee]
83
- if track[indexTrack.countDimensionsGapped, my[indexMy.leafConnectee]] == 0:
84
- gap1ndexCeilingIncrement()
85
- track[indexTrack.countDimensionsGapped, my[indexMy.leafConnectee]] += 1
86
-
87
- def dimension1ndexIncrement():
88
- my[indexMy.dimension1ndex] += 1
89
-
90
- def dimensionsUnconstrainedCondition():
91
- return connectionGraph[my[indexMy.dimension1ndex], my[indexMy.leaf1ndex], my[indexMy.leaf1ndex]] == my[indexMy.leaf1ndex]
92
-
93
- def dimensionsUnconstrainedIncrement():
94
- my[indexMy.dimensionsUnconstrained] += 1
95
-
96
- def filterCommonGaps():
97
- gapsWhere[my[indexMy.gap1ndex]] = gapsWhere[my[indexMy.indexMiniGap]]
98
- if track[indexTrack.countDimensionsGapped, gapsWhere[my[indexMy.indexMiniGap]]] == the[indexThe.dimensionsTotal] - my[indexMy.dimensionsUnconstrained]:
99
- activeGapIncrement()
100
- track[indexTrack.countDimensionsGapped, gapsWhere[my[indexMy.indexMiniGap]]] = 0
101
-
102
- def findGapsInitializeVariables():
103
- my[indexMy.dimensionsUnconstrained] = 0
104
- my[indexMy.gap1ndexCeiling] = track[indexTrack.gapRangeStart, my[indexMy.leaf1ndex] - 1]
105
- my[indexMy.dimension1ndex] = 1
106
-
107
- def foldsSubTotalsIncrement():
108
- foldsSubTotals[my[indexMy.taskIndex]] += the[indexThe.leavesTotal]
109
-
110
- def gap1ndexCeilingIncrement():
111
- my[indexMy.gap1ndexCeiling] += 1
112
-
113
- def indexMiniGapIncrement():
114
- my[indexMy.indexMiniGap] += 1
115
-
116
- def indexMiniGapInitialization():
117
- my[indexMy.indexMiniGap] = my[indexMy.gap1ndex]
118
-
119
- def insertUnconstrainedLeaf():
120
- my[indexMy.indexLeaf] = 0
121
- while my[indexMy.indexLeaf] < my[indexMy.leaf1ndex]:
122
- gapsWhere[my[indexMy.gap1ndexCeiling]] = my[indexMy.indexLeaf]
123
- my[indexMy.gap1ndexCeiling] += 1
124
- my[indexMy.indexLeaf] += 1
125
-
126
- def leafBelowSentinelIs1Condition():
127
- return track[indexTrack.leafBelow, 0] == 1
128
-
129
- def leafConnecteeInitialization():
130
- my[indexMy.leafConnectee] = connectionGraph[my[indexMy.dimension1ndex], my[indexMy.leaf1ndex], my[indexMy.leaf1ndex]]
131
-
132
- def leafConnecteeUpdate():
133
- my[indexMy.leafConnectee] = connectionGraph[my[indexMy.dimension1ndex], my[indexMy.leaf1ndex], track[indexTrack.leafBelow, my[indexMy.leafConnectee]]]
134
-
135
- def loopingLeavesConnectedToActiveLeaf():
136
- return my[indexMy.leafConnectee] != my[indexMy.leaf1ndex]
137
-
138
- def loopingTheDimensions():
139
- return my[indexMy.dimension1ndex] <= the[indexThe.dimensionsTotal]
140
-
141
- def loopingToActiveGapCeiling():
142
- return my[indexMy.indexMiniGap] < my[indexMy.gap1ndexCeiling]
143
-
144
- def placeLeaf():
145
- my[indexMy.gap1ndex] -= 1
146
- track[indexTrack.leafAbove, my[indexMy.leaf1ndex]] = gapsWhere[my[indexMy.gap1ndex]]
147
- track[indexTrack.leafBelow, my[indexMy.leaf1ndex]] = track[indexTrack.leafBelow, track[indexTrack.leafAbove, my[indexMy.leaf1ndex]]]
148
- track[indexTrack.leafBelow, track[indexTrack.leafAbove, my[indexMy.leaf1ndex]]] = my[indexMy.leaf1ndex]
149
- track[indexTrack.leafAbove, track[indexTrack.leafBelow, my[indexMy.leaf1ndex]]] = my[indexMy.leaf1ndex]
150
- track[indexTrack.gapRangeStart, my[indexMy.leaf1ndex]] = my[indexMy.gap1ndex]
151
- my[indexMy.leaf1ndex] += 1
152
-
153
- def placeLeafCondition():
154
- return my[indexMy.leaf1ndex] > 0
155
-
156
- def taskIndexCondition():
157
- return my[indexMy.leafConnectee] % the[indexThe.taskDivisions] == my[indexMy.taskIndex]
158
-
159
- def thereAreComputationDivisionsYouMightSkip():
160
- if computationDivisionsCondition():
161
- return True
162
- if activeLeafNotEqualToTaskDivisionsCondition():
163
- return True
164
- if taskIndexCondition():
165
- return True
166
- return False
167
-
168
- stateUniversal = outfitFoldings(listDimensions, computationDivisions=computationDivisions, CPUlimit=CPUlimit)
169
- connectionGraph: Final[numpy.ndarray] = stateUniversal['connectionGraph']
170
- foldsSubTotals = stateUniversal['foldsSubTotals']
171
- gapsWhere = stateUniversal['gapsWhere']
172
- my = stateUniversal['my']
173
- the: Final[numpy.ndarray] = stateUniversal['the']
174
- track = stateUniversal['track']
175
-
176
- if the[indexThe.taskDivisions] == int(False):
177
- doWhile()
178
- else:
179
- stateUniversal['my'] = my.copy()
180
- stateUniversal['gapsWhere'] = gapsWhere.copy()
181
- stateUniversal['track'] = track.copy()
182
- for indexSherpa in range(the[indexThe.taskDivisions]):
183
- my = stateUniversal['my'].copy()
184
- my[indexMy.taskIndex] = indexSherpa
185
- gapsWhere = stateUniversal['gapsWhere'].copy()
186
- track = stateUniversal['track'].copy()
187
- doWhile()
188
-
189
- return numpy.sum(foldsSubTotals).item()
190
-
191
- @enum.verify(enum.CONTINUOUS, enum.UNIQUE) if sys.version_info >= (3, 11) else lambda x: x
192
- class EnumIndices(enum.IntEnum):
193
- """Base class for index enums."""
194
- @staticmethod
195
- def _generate_next_value_(name, start, count, last_values):
196
- """0-indexed."""
197
- return count
198
-
199
- def __index__(self) -> int:
200
- """Adapt enum to the ultra-rare event of indexing a NumPy 'ndarray', which is not the
201
- same as `array.array`. See NumPy.org; I think it will be very popular someday."""
202
- return self
203
-
204
- class indexMy(EnumIndices):
205
- """Indices for dynamic values."""
206
- dimension1ndex = enum.auto()
207
- dimensionsUnconstrained = enum.auto()
208
- gap1ndex = enum.auto()
209
- gap1ndexCeiling = enum.auto()
210
- indexLeaf = enum.auto()
211
- indexMiniGap = enum.auto()
212
- leaf1ndex = enum.auto()
213
- leafConnectee = enum.auto()
214
- taskIndex = enum.auto()
215
-
216
- class indexThe(EnumIndices):
217
- """Indices for static values."""
218
- dimensionsTotal = enum.auto()
219
- leavesTotal = enum.auto()
220
- taskDivisions = enum.auto()
221
-
222
- class indexTrack(EnumIndices):
223
- """Indices for state tracking array."""
224
- leafAbove = enum.auto()
225
- leafBelow = enum.auto()
226
- countDimensionsGapped = enum.auto()
227
- gapRangeStart = enum.auto()
228
-
229
- class computationState(TypedDict):
230
- connectionGraph: NDArray[integer[Any]]
231
- foldsSubTotals: NDArray[integer[Any]]
232
- mapShape: Tuple[int, ...]
233
- my: NDArray[integer[Any]]
234
- gapsWhere: NDArray[integer[Any]]
235
- the: NDArray[integer[Any]]
236
- track: NDArray[integer[Any]]
237
-
238
- dtypeLarge = numpy.int64
239
- dtypeMedium = dtypeLarge
240
-
241
- def getLeavesTotal(listDimensions: Sequence[int]) -> int:
242
- """
243
- How many leaves are in the map.
244
-
245
- Parameters:
246
- listDimensions: A list of integers representing dimensions.
247
-
248
- Returns:
249
- productDimensions: The product of all positive integer dimensions.
250
- """
251
- listNonNegative = parseDimensions(listDimensions, 'listDimensions')
252
- listPositive = [dimension for dimension in listNonNegative if dimension > 0]
253
-
254
- if not listPositive:
255
- return 0
256
- else:
257
- productDimensions = 1
258
- for dimension in listPositive:
259
- if dimension > sys.maxsize // productDimensions:
260
- raise OverflowError(f"I received {dimension=} in {listDimensions=}, but the product of the dimensions exceeds the maximum size of an integer on this system.")
261
- productDimensions *= dimension
262
-
263
- return productDimensions
264
-
265
- def getTaskDivisions(computationDivisions: Optional[Union[int, str]], concurrencyLimit: int, CPUlimit: Optional[Union[bool, float, int]], listDimensions: Sequence[int]):
266
- if not computationDivisions:
267
- return 0
268
- else:
269
- leavesTotal = getLeavesTotal(listDimensions)
270
- taskDivisions = 0
271
- if isinstance(computationDivisions, int):
272
- taskDivisions = computationDivisions
273
- elif isinstance(computationDivisions, str):
274
- computationDivisions = computationDivisions.lower()
275
- if computationDivisions == "maximum":
276
- taskDivisions = leavesTotal
277
- elif computationDivisions == "cpu":
278
- taskDivisions = min(concurrencyLimit, leavesTotal)
279
- else:
280
- raise ValueError("Not my problem.")
281
-
282
- if taskDivisions > leavesTotal:
283
- raise ValueError("What are you doing?")
284
-
285
- return taskDivisions
286
-
287
- def makeConnectionGraph(listDimensions: Sequence[int], **keywordArguments: Optional[Type]) -> NDArray[integer[Any]]:
288
- datatype = keywordArguments.get('datatype', dtypeMedium)
289
- mapShape = validateListDimensions(listDimensions)
290
- leavesTotal = getLeavesTotal(mapShape)
291
- arrayDimensions = numpy.array(mapShape, dtype=datatype)
292
- dimensionsTotal = len(arrayDimensions)
293
-
294
- cumulativeProduct = numpy.multiply.accumulate([1] + mapShape, dtype=datatype)
295
- coordinateSystem = numpy.zeros((dimensionsTotal + 1, leavesTotal + 1), dtype=datatype)
296
- for dimension1ndex in range(1, dimensionsTotal + 1):
297
- for leaf1ndex in range(1, leavesTotal + 1):
298
- coordinateSystem[dimension1ndex, leaf1ndex] = ( ((leaf1ndex - 1) // cumulativeProduct[dimension1ndex - 1]) % arrayDimensions[dimension1ndex - 1] + 1 )
299
-
300
- connectionGraph = numpy.zeros((dimensionsTotal + 1, leavesTotal + 1, leavesTotal + 1), dtype=datatype)
301
- for dimension1ndex in range(1, dimensionsTotal + 1):
302
- for activeLeaf1ndex in range(1, leavesTotal + 1):
303
- for connectee1ndex in range(1, activeLeaf1ndex + 1):
304
- isFirstCoord = coordinateSystem[dimension1ndex, connectee1ndex] == 1
305
- isLastCoord = coordinateSystem[dimension1ndex, connectee1ndex] == arrayDimensions[dimension1ndex - 1]
306
- exceedsActive = connectee1ndex + cumulativeProduct[dimension1ndex - 1] > activeLeaf1ndex
307
- isEvenParity = (coordinateSystem[dimension1ndex, activeLeaf1ndex] & 1) == (coordinateSystem[dimension1ndex, connectee1ndex] & 1)
308
-
309
- if (isEvenParity and isFirstCoord) or (not isEvenParity and (isLastCoord or exceedsActive)):
310
- connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex
311
- elif isEvenParity and not isFirstCoord:
312
- connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex - cumulativeProduct[dimension1ndex - 1]
313
- elif not isEvenParity and not (isLastCoord or exceedsActive):
314
- connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex + cumulativeProduct[dimension1ndex - 1]
315
- else:
316
- connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex
317
- return connectionGraph
318
-
319
- def makeDataContainer(shape, datatype: Optional[Type] = None):
320
- if datatype is None:
321
- datatype = dtypeMedium
322
- return numpy.zeros(shape, dtype=datatype)
323
-
324
- def outfitFoldings(listDimensions: Sequence[int], computationDivisions: Optional[Union[int, str]] = None, CPUlimit: Optional[Union[bool, float, int]] = None, **keywordArguments: Optional[Type]) -> computationState:
325
- datatypeMedium = keywordArguments.get('datatypeMedium', dtypeMedium)
326
- datatypeLarge = keywordArguments.get('datatypeLarge', dtypeLarge)
327
-
328
- the = makeDataContainer(len(indexThe), datatypeMedium)
329
-
330
- mapShape = tuple(sorted(validateListDimensions(listDimensions)))
331
- the[indexThe.leavesTotal] = getLeavesTotal(mapShape)
332
- the[indexThe.dimensionsTotal] = len(mapShape)
333
- concurrencyLimit = setCPUlimit(CPUlimit)
334
- the[indexThe.taskDivisions] = getTaskDivisions(computationDivisions, concurrencyLimit, CPUlimit, listDimensions)
335
-
336
- stateInitialized = computationState(
337
- connectionGraph = makeConnectionGraph(mapShape, datatype=datatypeMedium),
338
- foldsSubTotals = makeDataContainer(the[indexThe.leavesTotal], datatypeLarge),
339
- mapShape = mapShape,
340
- my = makeDataContainer(len(indexMy), datatypeLarge),
341
- gapsWhere = makeDataContainer(int(the[indexThe.leavesTotal]) * int(the[indexThe.leavesTotal]) + 1, datatypeMedium),
342
- the = the,
343
- track = makeDataContainer((len(indexTrack), the[indexThe.leavesTotal] + 1), datatypeLarge)
344
- )
345
-
346
- stateInitialized['my'][indexMy.leaf1ndex] = 1
347
- return stateInitialized
348
-
349
- def parseDimensions(dimensions: Sequence[int], parameterName: str = 'unnamed parameter') -> List[int]:
350
- # listValidated = intInnit(dimensions, parameterName)
351
- listNOTValidated = dimensions if isinstance(dimensions, (list, tuple)) else list(dimensions)
352
- listNonNegative = []
353
- for dimension in listNOTValidated:
354
- if dimension < 0:
355
- raise ValueError(f"Dimension {dimension} must be non-negative")
356
- listNonNegative.append(dimension)
357
- if not listNonNegative:
358
- raise ValueError("At least one dimension must be non-negative")
359
- return listNonNegative
360
-
361
- def setCPUlimit(CPUlimit: Union[bool, float, int, None]) -> int:
362
- # if not (CPUlimit is None or isinstance(CPUlimit, (bool, int, float))):
363
- # CPUlimit = oopsieKwargsie(CPUlimit)
364
- # concurrencyLimit = defineConcurrencyLimit(CPUlimit)
365
- # numba.set_num_threads(concurrencyLimit)
366
- concurrencyLimitHARDCODED = 1
367
- concurrencyLimit = concurrencyLimitHARDCODED
368
- return concurrencyLimit
369
-
370
- def validateListDimensions(listDimensions: Sequence[int]) -> List[int]:
371
- if not listDimensions:
372
- raise ValueError(f"listDimensions is a required parameter.")
373
- listNonNegative = parseDimensions(listDimensions, 'listDimensions')
374
- dimensionsValid = [dimension for dimension in listNonNegative if dimension > 0]
375
- if len(dimensionsValid) < 2:
376
- raise NotImplementedError(f"This function requires listDimensions, {listDimensions}, to have at least two dimensions greater than 0. You may want to look at https://oeis.org/.")
377
- return sorted(dimensionsValid)
@@ -1,132 +0,0 @@
1
- from typing import List
2
- import numba
3
- import numpy
4
-
5
- @numba.jit(cache=True, nopython=True, fastmath=True)
6
- def countFolds(listDimensions: List[int]) -> int:
7
- """
8
- Count the number of distinct ways to fold a map with at least two positive dimensions.
9
-
10
- Parameters:
11
- listDimensions: A list of integers representing the dimensions of the map. Error checking and DRY code are impermissible in the numba and jax universes. Validate the list yourself before passing here. There might be some tools for that in this package unless I have become a pyL33t coder.
12
-
13
- Returns:
14
- foldsTotal: The total number of distinct folds for the given map dimensions.
15
- """
16
- def integerSmall(value) -> numpy.uint8:
17
- return numpy.uint8(value)
18
-
19
- def integerLarge(value) -> numpy.uint64:
20
- return numpy.uint64(value)
21
-
22
- dtypeMedium = numpy.uint8
23
- dtypeMaximum = numpy.uint16
24
-
25
- leavesTotal = integerSmall(1)
26
- for 个 in listDimensions:
27
- leavesTotal = leavesTotal * integerSmall(个)
28
- dimensionsTotal = integerSmall(len(listDimensions))
29
-
30
- """How to build a leaf connection graph, also called a "Cartesian Product Decomposition"
31
- or a "Dimensional Product Mapping", with sentinels:
32
- Step 1: find the cumulative product of the map's dimensions"""
33
- cumulativeProduct = numpy.ones(dimensionsTotal + 1, dtype=dtypeMedium)
34
- for dimension1ndex in range(1, dimensionsTotal + 1):
35
- cumulativeProduct[dimension1ndex] = cumulativeProduct[dimension1ndex - 1] * listDimensions[dimension1ndex - 1]
36
-
37
- """Step 2: for each dimension, create a coordinate system """
38
- """coordinateSystem[dimension1ndex, leaf1ndex] holds the dimension1ndex-th coordinate of leaf leaf1ndex"""
39
- coordinateSystem = numpy.zeros((dimensionsTotal + 1, leavesTotal + 1), dtype=dtypeMedium)
40
- for dimension1ndex in range(1, dimensionsTotal + 1):
41
- for leaf1ndex in range(1, leavesTotal + 1):
42
- coordinateSystem[dimension1ndex, leaf1ndex] = ((leaf1ndex - 1) // cumulativeProduct[dimension1ndex - 1]) % listDimensions[dimension1ndex - 1] + 1
43
-
44
- """Step 3: create a huge empty connection graph"""
45
- connectionGraph = numpy.zeros((dimensionsTotal + 1, leavesTotal + 1, leavesTotal + 1), dtype=dtypeMedium)
46
-
47
- """Step for... for... for...: fill the connection graph"""
48
- for dimension1ndex in range(1, dimensionsTotal + 1):
49
- for leaf1ndex in range(1, leavesTotal + 1):
50
- for leafConnectee in range(1, leaf1ndex + 1):
51
- connectionGraph[dimension1ndex, leaf1ndex, leafConnectee] = (0 if leafConnectee == 0
52
- else ((leafConnectee if coordinateSystem[dimension1ndex, leafConnectee] == 1
53
- else leafConnectee - cumulativeProduct[dimension1ndex - 1])
54
- if (coordinateSystem[dimension1ndex, leaf1ndex] & 1) == (coordinateSystem[dimension1ndex, leafConnectee] & 1)
55
- else (leafConnectee if coordinateSystem[dimension1ndex, leafConnectee] == listDimensions[dimension1ndex-1]
56
- or leafConnectee + cumulativeProduct[dimension1ndex - 1] > leaf1ndex
57
- else leafConnectee + cumulativeProduct[dimension1ndex - 1])))
58
-
59
- """Indices of array `track` (to "track" the execution state), which is a collection of one-dimensional arrays each of length `leavesTotal + 1`."""
60
- leafAbove = numba.literally(0)
61
- leafBelow = numba.literally(1)
62
- countDimensionsGapped = numba.literally(2)
63
- gapRangeStart = numba.literally(3)
64
- track = numpy.zeros((4, leavesTotal + 1), dtype=dtypeMedium)
65
-
66
- gapsWhere = numpy.zeros(integerLarge(integerLarge(leavesTotal) * integerLarge(leavesTotal) + 1), dtype=dtypeMaximum)
67
-
68
- foldsTotal = integerLarge(0)
69
- leaf1ndex = integerSmall(1)
70
- gap1ndex = integerSmall(0)
71
-
72
- while leaf1ndex > 0:
73
- if leaf1ndex <= 1 or track[leafBelow, 0] == 1:
74
- if leaf1ndex > leavesTotal:
75
- foldsTotal += leavesTotal
76
- else:
77
- dimensionsUnconstrained = integerSmall(0)
78
- """Track possible gaps for leaf1ndex in each section"""
79
- gap1ndexCeiling = track[gapRangeStart, leaf1ndex - 1]
80
-
81
- """Count possible gaps for leaf1ndex in each section"""
82
- dimension1ndex = integerSmall(1)
83
- while dimension1ndex <= dimensionsTotal:
84
- if connectionGraph[dimension1ndex, leaf1ndex, leaf1ndex] == leaf1ndex:
85
- dimensionsUnconstrained += 1
86
- else:
87
- leafConnectee = connectionGraph[dimension1ndex, leaf1ndex, leaf1ndex]
88
- while leafConnectee != leaf1ndex:
89
- gapsWhere[gap1ndexCeiling] = leafConnectee
90
- if track[countDimensionsGapped, leafConnectee] == 0:
91
- gap1ndexCeiling += 1
92
- track[countDimensionsGapped, leafConnectee] += 1
93
- leafConnectee = connectionGraph[dimension1ndex, leaf1ndex, track[leafBelow, leafConnectee]]
94
- dimension1ndex += 1
95
-
96
- """If leaf1ndex is unconstrained in all sections, it can be inserted anywhere"""
97
- if dimensionsUnconstrained == dimensionsTotal:
98
- indexLeaf = integerSmall(0)
99
- while indexLeaf < leaf1ndex:
100
- gapsWhere[gap1ndexCeiling] = indexLeaf
101
- gap1ndexCeiling += 1
102
- indexLeaf += 1
103
-
104
- """Filter gaps that are common to all sections"""
105
- indexMiniGap = gap1ndex
106
- while indexMiniGap < gap1ndexCeiling:
107
- gapsWhere[gap1ndex] = gapsWhere[indexMiniGap]
108
- if track[countDimensionsGapped, gapsWhere[indexMiniGap]] == dimensionsTotal - dimensionsUnconstrained:
109
- gap1ndex += 1
110
- """Reset track[countDimensionsGapped] for next iteration"""
111
- track[countDimensionsGapped, gapsWhere[indexMiniGap]] = 0
112
- indexMiniGap += 1
113
-
114
- """Recursive backtracking steps"""
115
- while leaf1ndex > 0 and gap1ndex == track[gapRangeStart, leaf1ndex - 1]:
116
- leaf1ndex -= 1
117
- track[leafBelow, track[leafAbove, leaf1ndex]] = track[leafBelow, leaf1ndex]
118
- track[leafAbove, track[leafBelow, leaf1ndex]] = track[leafAbove, leaf1ndex]
119
-
120
- """Place leaf in valid position"""
121
- if leaf1ndex > 0:
122
- gap1ndex -= 1
123
- track[leafAbove, leaf1ndex] = gapsWhere[gap1ndex]
124
- track[leafBelow, leaf1ndex] = track[leafBelow, track[leafAbove, leaf1ndex]]
125
- track[leafBelow, track[leafAbove, leaf1ndex]] = leaf1ndex
126
- track[leafAbove, track[leafBelow, leaf1ndex]] = leaf1ndex
127
- """Save current gap index"""
128
- track[gapRangeStart, leaf1ndex] = gap1ndex
129
- """Move to next leaf"""
130
- leaf1ndex += 1
131
-
132
- return int(foldsTotal)
@@ -1,120 +0,0 @@
1
- """
2
- Ported from the Java version by Sean A. Irvine:
3
- https://github.com/archmageirvine/joeis/blob/80e3e844b11f149704acbab520bc3a3a25ac34ff/src/irvine/oeis/a001/A001415.java
4
-
5
- Citation: mapFolding/citations/jOEIS.bibtex
6
- """
7
- def foldings(p: list[int], res: int = 0, mod: int = 0) -> int:
8
- """
9
- Compute the total number of foldings for a map with dimensions specified in p.
10
-
11
- Parameters:
12
- p: List of integers representing the dimensions of the map.
13
- res: Residue for modulo operation (integer).
14
- mod: Modulus for modulo operation (integer).
15
-
16
- Returns:
17
- total_count: The total number of foldings (integer).
18
- """
19
- n = 1 # Total number of leaves
20
- d = len(p) # Number of dimensions
21
- for dimension in p:
22
- n *= dimension
23
-
24
- # Initialize arrays/lists
25
- A = [0] * (n + 1) # Leaf above leaf m
26
- B = [0] * (n + 1) # Leaf below leaf m
27
- count = [0] * (n + 1) # Counts for potential gaps
28
- gapter = [0] * (n + 1) # Indices for gap stack per leaf
29
- gap = [0] * (n * n + 1) # Stack of potential gaps
30
-
31
- # Compute arrays P, C, D as per the algorithm
32
- P = [1] * (d + 1)
33
- for i in range(1, d + 1):
34
- P[i] = P[i - 1] * p[i - 1]
35
-
36
- # C[i][m] holds the i-th coordinate of leaf m
37
- C = [[0] * (n + 1) for _ in range(d + 1)]
38
- for i in range(1, d + 1):
39
- for m in range(1, n + 1):
40
- C[i][m] = ((m - 1) // P[i - 1]) - ((m - 1) // P[i]) * p[i - 1] + 1
41
-
42
- # D[i][l][m] computes the leaf connected to m in section i when inserting l
43
- D = [[[0] * (n + 1) for _ in range(n + 1)] for _ in range(d + 1)]
44
- for i in range(1, d + 1):
45
- for l in range(1, n + 1):
46
- for m in range(1, l + 1):
47
- delta = C[i][l] - C[i][m]
48
- if delta % 2 == 0:
49
- # If delta is even
50
- if C[i][m] == 1:
51
- D[i][l][m] = m
52
- else:
53
- D[i][l][m] = m - P[i - 1]
54
- else:
55
- # If delta is odd
56
- if C[i][m] == p[i - 1] or m + P[i - 1] > l:
57
- D[i][l][m] = m
58
- else:
59
- D[i][l][m] = m + P[i - 1]
60
-
61
- # Initialize variables for backtracking
62
- total_count = 0 # Total number of foldings
63
- g = 0 # Gap index
64
- l = 1 # Current leaf
65
-
66
- # Start backtracking loop
67
- while l > 0:
68
- # If we have processed all leaves, increment total count
69
- if l > n:
70
- total_count += 1
71
- else:
72
- dd = 0 # Number of sections where leaf l is unconstrained
73
- gg = g # Temporary gap index
74
- g = gapter[l - 1] # Reset gap index for current leaf
75
-
76
- # Count possible gaps for leaf l in each section
77
- for i in range(1, d + 1):
78
- if D[i][l][l] == l:
79
- dd += 1
80
- else:
81
- m = D[i][l][l]
82
- while m != l:
83
- if mod == 0 or l != mod or m % mod == res:
84
- gap[gg] = m
85
- if count[m] == 0:
86
- gg += 1
87
- count[m] += 1
88
- m = D[i][l][B[m]]
89
-
90
- # If leaf l is unconstrained in all sections, it can be inserted anywhere
91
- if dd == d:
92
- for m in range(l):
93
- gap[gg] = m
94
- gg += 1
95
-
96
- # Filter gaps that are common to all sections
97
- for j in range(g, gg):
98
- gap[g] = gap[j]
99
- if count[gap[j]] == d - dd:
100
- g += 1
101
- count[gap[j]] = 0 # Reset count for next iteration
102
-
103
- # Recursive backtracking steps
104
- while l > 0 and g == gapter[l - 1]:
105
- # No more gaps to try, backtrack to previous leaf
106
- l -= 1
107
- B[A[l]] = B[l]
108
- A[B[l]] = A[l]
109
-
110
- if l > 0:
111
- # Try next gap for leaf l
112
- g -= 1
113
- A[l] = gap[g]
114
- B[l] = B[A[l]]
115
- B[A[l]] = l
116
- A[B[l]] = l
117
- gapter[l] = g # Save current gap index
118
- l += 1 # Move to next leaf
119
-
120
- return total_count