mapFolding 0.2.5__py3-none-any.whl → 0.2.7__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 (35) hide show
  1. {mapFolding-0.2.5.dist-info → mapFolding-0.2.7.dist-info}/METADATA +21 -7
  2. mapFolding-0.2.7.dist-info/RECORD +19 -0
  3. mapFolding-0.2.7.dist-info/top_level.txt +3 -0
  4. {mapFolding/someAssemblyRequired → someAssemblyRequired}/inlineAfunction.py +3 -3
  5. {mapFolding/someAssemblyRequired → someAssemblyRequired}/jobsAndTasks.py +5 -6
  6. {mapFolding/someAssemblyRequired → someAssemblyRequired}/makeNumbaJob.py +57 -31
  7. mapFolding/__init__.py +0 -12
  8. mapFolding/babbage.py +0 -35
  9. mapFolding/beDRY.py +0 -325
  10. mapFolding/importSelector.py +0 -7
  11. mapFolding/lovelace.py +0 -213
  12. mapFolding/oeis.py +0 -323
  13. mapFolding/startHere.py +0 -50
  14. mapFolding/theSSOT.py +0 -75
  15. mapFolding-0.2.5.dist-info/RECORD +0 -33
  16. mapFolding-0.2.5.dist-info/top_level.txt +0 -2
  17. tests/__init__.py +0 -1
  18. tests/conftest.py +0 -345
  19. tests/pythons_idiotic_namespace.py +0 -1
  20. tests/test_oeis.py +0 -194
  21. tests/test_other.py +0 -268
  22. tests/test_tasks.py +0 -31
  23. {mapFolding/benchmarks → benchmarks}/benchmarking.py +0 -0
  24. {mapFolding-0.2.5.dist-info → mapFolding-0.2.7.dist-info}/WHEEL +0 -0
  25. {mapFolding-0.2.5.dist-info → mapFolding-0.2.7.dist-info}/entry_points.txt +0 -0
  26. {mapFolding/reference → reference}/flattened.py +0 -0
  27. {mapFolding/reference → reference}/hunterNumba.py +0 -0
  28. {mapFolding/reference → reference}/irvineJavaPort.py +0 -0
  29. {mapFolding/reference → reference}/jax.py +0 -0
  30. {mapFolding/reference → reference}/lunnan.py +0 -0
  31. {mapFolding/reference → reference}/lunnanNumpy.py +0 -0
  32. {mapFolding/reference → reference}/lunnanWhile.py +0 -0
  33. {mapFolding/reference → reference}/rotatedEntryPoint.py +0 -0
  34. {mapFolding/reference → reference}/total_countPlus1vsPlusN.py +0 -0
  35. {mapFolding/someAssemblyRequired → someAssemblyRequired}/makeNuitkaSource.py +0 -0
@@ -1,18 +1,32 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: mapFolding
3
- Version: 0.2.5
3
+ Version: 0.2.7
4
4
  Summary: Count distinct ways to fold a map (or a strip of stamps)
5
5
  Author-email: Hunter Hogan <HunterHogan@pm.me>
6
- Project-URL: homepage, https://github.com/hunterhogan/mapFolding
7
- Requires-Python: <3.13,>=3.10
6
+ License: CC-BY-NC-4.0
7
+ Project-URL: Homepage, https://github.com/hunterhogan/mapFolding
8
+ Project-URL: Donate, https://www.patreon.com/integrated
9
+ Keywords: A001415,A001416,A001417,A001418,A195646,folding,map folding,OEIS,stamp folding
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: Intended Audience :: Other Audience
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Natural Language :: English
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python
19
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: <3.14,>=3.10
8
22
  Description-Content-Type: text/markdown
9
23
  Requires-Dist: numba
10
24
  Requires-Dist: numpy
11
- Requires-Dist: Z0Z-tools
25
+ Requires-Dist: Z0Z_tools
12
26
  Provides-Extra: benchmark
13
- Requires-Dist: pandas; extra == "benchmark"
14
- Requires-Dist: jupyter; extra == "benchmark"
15
27
  Requires-Dist: ipywidgets; extra == "benchmark"
28
+ Requires-Dist: jupyter; extra == "benchmark"
29
+ Requires-Dist: pandas; extra == "benchmark"
16
30
  Requires-Dist: tqdm; extra == "benchmark"
17
31
  Provides-Extra: testing
18
32
  Requires-Dist: pytest; extra == "testing"
@@ -40,7 +54,7 @@ The directory [mapFolding/reference](https://github.com/hunterhogan/mapFolding/b
40
54
 
41
55
  ## Simple, easy usage based on OEIS IDs
42
56
 
43
- `mapFolding` directly implements some IDs from _The On-Line Encyclopedia of Integer Sequences_.
57
+ `mapFolding` directly implements some IDs from _The On-Line Encyclopedia of Integer Sequences_ ([BibTex](https://github.com/hunterhogan/mapFolding/blob/main/mapFolding/citations/oeis.bibtex) citation).
44
58
 
45
59
  ### Usage: command line
46
60
 
@@ -0,0 +1,19 @@
1
+ benchmarks/benchmarking.py,sha256=HD_0NSvuabblg94ftDre6LFnXShTe8MYj3hIodW-zV0,3076
2
+ reference/flattened.py,sha256=X9nvRzg7YDcpCtSDTL4YiidjshlX9rg2e6JVCY6i2u0,16547
3
+ reference/hunterNumba.py,sha256=0giUyqAFzP-XKcq3Kz8wIWCK0BVFhjABVJ1s-w4Jhu0,7109
4
+ reference/irvineJavaPort.py,sha256=Sj-63Z-OsGuDoEBXuxyjRrNmmyl0d7Yz_XuY7I47Oyg,4250
5
+ reference/jax.py,sha256=bB34dGdi3VSz4cRFbmCPn_erAmQ3FyrSED8uJ7CsES0,14961
6
+ reference/lunnan.py,sha256=XEcql_gxvCCghb6Or3qwmPbn4IZUbZTaSmw_fUjRxZE,5037
7
+ reference/lunnanNumpy.py,sha256=HqDgSwTOZA-G0oophOEfc4zs25Mv4yw2aoF1v8miOLk,4653
8
+ reference/lunnanWhile.py,sha256=7NY2IKO5XBgol0aWWF_Fi-7oTL9pvu_z6lB0TF1uVHk,4063
9
+ reference/rotatedEntryPoint.py,sha256=z0QyDQtnMvXNj5ntWzzJUQUMFm1-xHGLVhtYzwmczUI,11530
10
+ reference/total_countPlus1vsPlusN.py,sha256=usenM8Yn_G1dqlPl7NKKkcnbohBZVZBXTQRm2S3_EDA,8106
11
+ someAssemblyRequired/inlineAfunction.py,sha256=_hGAxVSVUAKCsNT92p0--Y636HkudpxHDEClXKrmmNE,6181
12
+ someAssemblyRequired/jobsAndTasks.py,sha256=zHgqvY4GHiCmH1fQrOHxsyDFUWoOcNtLAKPLwL6NVvU,2155
13
+ someAssemblyRequired/makeNuitkaSource.py,sha256=jTK34OWzm6OsgFPd2mHwETxFo2X83io0M4YiEHRgk3U,3262
14
+ someAssemblyRequired/makeNumbaJob.py,sha256=L1JORHfVKjBve7GjlE4-JMnzT7wJGJISGzLbWyRCyxU,5899
15
+ mapFolding-0.2.7.dist-info/METADATA,sha256=i3nAtGhadvid_ODpCN9uXk9e4L3zQhXJfuElSQUmY50,7425
16
+ mapFolding-0.2.7.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
17
+ mapFolding-0.2.7.dist-info/entry_points.txt,sha256=F3OUeZR1XDTpoH7k3wXuRb3KF_kXTTeYhu5AGK1SiOQ,146
18
+ mapFolding-0.2.7.dist-info/top_level.txt,sha256=yHhQq-bIJhB4pZcof5hXDTIjan0nxcFuOEWb7gy1DuU,42
19
+ mapFolding-0.2.7.dist-info/RECORD,,
@@ -0,0 +1,3 @@
1
+ benchmarks
2
+ reference
3
+ someAssemblyRequired
@@ -1,11 +1,11 @@
1
- from mapFolding import indexMy, indexThe, indexTrack
1
+ from mapFolding import indexMy, indexTrack
2
2
  import ast
3
3
  import copy
4
4
  import pathlib
5
5
 
6
6
  def getDictionaryEnumValues():
7
7
  dictionaryEnumValues = {}
8
- for enumIndex in [indexMy, indexThe, indexTrack]:
8
+ for enumIndex in [indexMy, indexTrack]:
9
9
  for memberName, memberValue in enumIndex._member_map_.items():
10
10
  dictionaryEnumValues[f"{enumIndex.__name__}.{memberName}.value"] = memberValue.value
11
11
  return dictionaryEnumValues
@@ -125,7 +125,7 @@ def Z0Z_inlineMapFolding():
125
125
 
126
126
  listPathFilenamesDestination: list[pathlib.Path] = []
127
127
  for callableTarget in listCallables:
128
- pathFilenameDestination = pathFilenameSource.with_stem(callableTarget)
128
+ pathFilenameDestination = pathFilenameSource.parent / "someAssemblyRequired" / pathFilenameSource.with_stem(callableTarget).name
129
129
  codeInlined = inlineFunctions(codeSource, callableTarget, dictionaryEnumValues)
130
130
  pathFilenameDestination.write_text(codeInlined)
131
131
  listPathFilenamesDestination.append(pathFilenameDestination)
@@ -1,10 +1,10 @@
1
- from typing import Any, Optional, Sequence, Type, Union
1
+ from typing import Any, Optional, Sequence, Type
2
2
 
3
3
  def Z0Z_makeJob(listDimensions: Sequence[int], **keywordArguments: Optional[Type[Any]]):
4
4
  from mapFolding import outfitCountFolds
5
5
  stateUniversal = outfitCountFolds(listDimensions, computationDivisions=None, CPUlimit=None, **keywordArguments)
6
- from mapFolding.countInitialize import countInitialize
7
- countInitialize(stateUniversal['connectionGraph'], stateUniversal['gapsWhere'], stateUniversal['my'], stateUniversal['the'], stateUniversal['track'])
6
+ from mapFolding.someAssemblyRequired.countInitializeNoNumba import countInitialize
7
+ countInitialize(stateUniversal['connectionGraph'], stateUniversal['gapsWhere'], stateUniversal['my'], stateUniversal['track'])
8
8
  from mapFolding import getPathFilenameFoldsTotal
9
9
  pathFilenameChopChop = getPathFilenameFoldsTotal(stateUniversal['mapShape'])
10
10
  import pathlib
@@ -35,11 +35,10 @@ def runJob(pathFilename):
35
35
  gapsWhere: numpy.ndarray = stateJob['gapsWhere']
36
36
  my: numpy.ndarray = stateJob['my']
37
37
  pathFilenameFoldsTotal: Final[Path] = stateJob['pathFilenameFoldsTotal']
38
- the: Final[numpy.ndarray] = stateJob['the']
39
38
  track: numpy.ndarray = stateJob['track']
40
39
 
41
- from mapFolding.countSequentialNoNumba import countSequential
42
- countSequential(connectionGraph, foldsSubTotals, gapsWhere, my, the, track)
40
+ from mapFolding.someAssemblyRequired.countSequentialNoNumba import countSequential
41
+ countSequential(connectionGraph, foldsSubTotals, gapsWhere, my, track)
43
42
 
44
43
  print(foldsSubTotals.sum().item())
45
44
  Path(pathFilenameFoldsTotal).parent.mkdir(parents=True, exist_ok=True)
@@ -1,9 +1,12 @@
1
1
  """Create a python module hardcoded to compute a map's foldsTotal.
2
- NumPy ndarray.
3
- Numba optimized.
4
- Absolutely no other imports.
2
+ - NumPy ndarray.
3
+ - Numba optimized.
4
+ - Absolutely no other imports.
5
+
6
+ Can create LLVM IR from the module: of unknown utility.
5
7
  """
6
- from mapFolding import datatypeLarge, dtypeLarge, dtypeDefault
8
+ # from mapFolding import dtypeDefault, dtypeSmall
9
+ from mapFolding import make_dtype, datatypeLarge, dtypeLarge
7
10
  from mapFolding.someAssemblyRequired.inlineAfunction import Z0Z_inlineMapFolding
8
11
  from mapFolding.someAssemblyRequired.jobsAndTasks import Z0Z_makeJob
9
12
  import importlib
@@ -11,30 +14,51 @@ import llvmlite.binding
11
14
  import numpy
12
15
  import pathlib
13
16
  import pickle
17
+ import python_minifier
14
18
 
15
- listDimensions = [3,7]
19
+ listDimensions = [5,5]
16
20
 
17
21
  # NOTE this overwrites files
18
22
  Z0Z_inlineMapFolding()
19
23
 
20
24
  identifierCallableLaunch = "goGoGadgetAbsurdity"
21
25
 
22
- def archivistFormatsArrayToCode(arrayTarget: numpy.ndarray, identifierName: str) -> str:
23
- """Format numpy array into a code string that recreates the array."""
24
- arrayAsTypeStr = numpy.array2string(arrayTarget, threshold=10000, max_line_width=200, separator=',')
25
- return f"{identifierName} = numpy.array({arrayAsTypeStr}, dtype=numpy.{arrayTarget.dtype})"
26
+ def convertNDArrayToStr(arrayTarget: numpy.ndarray, identifierName: str) -> str:
27
+ arrayAsTypeStr = numpy.array2string(arrayTarget, threshold=100000, max_line_width=200, separator=',')
28
+ stringMinimized = python_minifier.minify(arrayAsTypeStr)
29
+ commaZeroMaximum = arrayTarget.shape[-1] - 1
30
+ stringMinimized = stringMinimized.replace('[0' + ',0'*commaZeroMaximum + ']', '[0]*'+str(commaZeroMaximum+1))
31
+ for countZeros in range(commaZeroMaximum, 2, -1):
32
+ stringMinimized = stringMinimized.replace(',0'*countZeros + ']', ']+[0]*'+str(countZeros))
33
+ return f"{identifierName} = numpy.array({stringMinimized}, dtype=numpy.{arrayTarget.dtype})"
26
34
 
27
35
  def writeModuleWithNumba(listDimensions):
28
36
  numpy_dtypeLarge = dtypeLarge
29
- numpy_dtypeDefault = dtypeDefault
30
-
31
- parametersNumba = f"numba.types.{datatypeLarge}(), cache=True, parallel=False, boundscheck=False, \
32
- error_model='numpy', fastmath=True, nogil=True, nopython=True, _nrt=True, forceinline=True, \
33
- inline=True, looplift=True, no_cfunc_wrapper=False, no_cpython_wrapper=False"
34
-
35
- pathFilenameData = Z0Z_makeJob(listDimensions, datatypeDefault=numpy_dtypeDefault, datatypeLarge=numpy_dtypeLarge)
36
-
37
- pathFilenameAlgorithm = pathlib.Path('/apps/mapFolding/mapFolding/countSequentialNoNumba.py')
37
+ # numpy_dtypeDefault = dtypeDefault
38
+ datatypeDefault = 'uint8'
39
+ numpy_dtypeDefault = make_dtype(datatypeDefault)
40
+ numpy_dtypeSmall = numpy_dtypeDefault
41
+ # forceinline=True might actually be useful
42
+ parametersNumba = f"numba.types.{datatypeLarge}(), \
43
+ cache=True, \
44
+ nopython=True, \
45
+ fastmath=True, \
46
+ forceinline=True, \
47
+ inline='always', \
48
+ looplift=False, \
49
+ _nrt=True, \
50
+ error_model='numpy', \
51
+ parallel=False, \
52
+ boundscheck=False, \
53
+ no_cfunc_wrapper=False, \
54
+ no_cpython_wrapper=False, \
55
+ "
56
+ # no_cfunc_wrapper=True, \
57
+ # no_cpython_wrapper=True, \
58
+
59
+ pathFilenameData = Z0Z_makeJob(listDimensions, datatypeDefault=numpy_dtypeDefault, datatypeLarge=numpy_dtypeLarge, datatypeSmall=numpy_dtypeSmall)
60
+
61
+ pathFilenameAlgorithm = pathlib.Path('/apps/mapFolding/mapFolding/someAssemblyRequired/countSequentialNoNumba.py')
38
62
  pathFilenameDestination = pathFilenameData.with_stem(pathFilenameData.parent.name).with_suffix(".py")
39
63
 
40
64
  lineNumba = f"@numba.jit({parametersNumba})"
@@ -49,16 +73,16 @@ def writeModuleWithNumba(listDimensions):
49
73
  ImaIndent = ' '
50
74
  linesDataDynamic = """"""
51
75
  linesDataDynamic = "\n".join([linesDataDynamic
52
- , ImaIndent + archivistFormatsArrayToCode(stateJob['my'], 'my')
53
- , ImaIndent + archivistFormatsArrayToCode(stateJob['foldsSubTotals'], 'foldsSubTotals')
54
- , ImaIndent + archivistFormatsArrayToCode(stateJob['gapsWhere'], 'gapsWhere')
55
- , ImaIndent + archivistFormatsArrayToCode(stateJob['track'], 'track')
76
+ , ImaIndent + f"foldsTotal = numba.types.{datatypeLarge}(0)"
77
+ , ImaIndent + convertNDArrayToStr(stateJob['my'], 'my')
78
+ , ImaIndent + convertNDArrayToStr(stateJob['foldGroups'], 'foldGroups')
79
+ , ImaIndent + convertNDArrayToStr(stateJob['gapsWhere'], 'gapsWhere')
80
+ , ImaIndent + convertNDArrayToStr(stateJob['track'], 'track')
56
81
  ])
57
82
 
58
83
  linesDataStatic = """"""
59
84
  linesDataStatic = "\n".join([linesDataStatic
60
- , ImaIndent + archivistFormatsArrayToCode(stateJob['the'], 'the')
61
- , ImaIndent + archivistFormatsArrayToCode(stateJob['connectionGraph'], 'connectionGraph')
85
+ , ImaIndent + convertNDArrayToStr(stateJob['connectionGraph'], 'connectionGraph')
62
86
  ])
63
87
 
64
88
  pathFilenameFoldsTotal: pathlib.Path = stateJob['pathFilenameFoldsTotal']
@@ -79,26 +103,28 @@ def writeModuleWithNumba(listDimensions):
79
103
  , lineSource
80
104
  ])
81
105
 
82
- lineReturn = f"{ImaIndent}return foldsSubTotals.sum().item()"
83
-
84
106
  linesLaunch = """"""
85
107
  linesLaunch = linesLaunch + f"""
86
108
  if __name__ == '__main__':
87
- foldsTotal = {identifierCallableLaunch}()"""
109
+ import time
110
+ timeStart = time.perf_counter()
111
+ {identifierCallableLaunch}()
112
+ print(time.perf_counter() - timeStart)"""
88
113
 
89
114
  linesWriteFoldsTotal = """"""
90
115
  linesWriteFoldsTotal = "\n".join([linesWriteFoldsTotal
116
+ , " foldsTotal = foldGroups[0:-1].sum() * foldGroups[-1]"
91
117
  , " print(foldsTotal)"
92
- , f" open('{pathFilenameFoldsTotal.as_posix()}', 'w').write(str(foldsTotal))"
118
+ , " with numba.objmode():"
119
+ , f" open('{pathFilenameFoldsTotal.as_posix()}', 'w').write(str(foldsTotal))"
120
+ , " return foldsTotal"
93
121
  ])
94
122
 
95
123
  linesAll = "\n".join([
96
124
  linesImport
97
125
  , linesAlgorithm
98
- , f"{ImaIndent}print(foldsSubTotals.sum().item())"
99
- , lineReturn
100
- , linesLaunch
101
126
  , linesWriteFoldsTotal
127
+ , linesLaunch
102
128
  ])
103
129
 
104
130
  pathFilenameDestination.write_text(linesAll)
mapFolding/__init__.py DELETED
@@ -1,12 +0,0 @@
1
- from .theSSOT import *
2
- from Z0Z_tools import defineConcurrencyLimit, intInnit, oopsieKwargsie
3
- from .beDRY import getFilenameFoldsTotal, getPathFilenameFoldsTotal, outfitCountFolds, saveFoldsTotal
4
- from .startHere import countFolds
5
- from .oeis import oeisIDfor_n, getOEISids, clearOEIScache
6
-
7
- __all__ = [
8
- 'clearOEIScache',
9
- 'countFolds',
10
- 'getOEISids',
11
- 'oeisIDfor_n',
12
- ]
mapFolding/babbage.py DELETED
@@ -1,35 +0,0 @@
1
- from mapFolding.importSelector import countSequential, countParallel, countInitialize
2
- from mapFolding import indexThe
3
- from numpy import integer
4
- from numpy.typing import NDArray
5
- from typing import Any, Tuple
6
- import numba
7
- import numpy
8
-
9
- @numba.jit(cache=True)
10
- def _countFolds(connectionGraph: NDArray[integer[Any]], foldsSubTotals: NDArray[integer[Any]], gapsWhere: NDArray[integer[Any]], mapShape: Tuple[int, ...], my: NDArray[integer[Any]], the: NDArray[integer[Any]], track: NDArray[integer[Any]]):
11
- """
12
- What in tarnation is this stupid module and function?
13
-
14
- - This function is not in the same module as `countFolds` so that we can delay Numba just-in-time (jit) compilation of this function and the finalization of its settings until we are ready.
15
- - This function is not in the same module as `countFoldsCompiled`, which is the function that does the hard, so that we can delay `numba.jit` compilation of `countFoldsCompiled`.
16
- - `countFoldsCompiled` is not merely "jitted", it is super jitted, which makes it too arrogant to talk to plebian Python functions. It will, however, reluctantly talk to basic jitted functions.
17
- - The function in this module is jitted, so it can talk to `countFoldsCompiled`, and because it isn't so arrogant, it will talk to the low-class `countFolds` with only a few restrictions, such as:
18
- - No `TypedDict`
19
- - No Python v 3.13
20
- - The plebs must clean up their own memory problems
21
- - No oversized integers
22
- - No global variables, only global constants
23
- - They don't except pleb nonlocal variables either
24
- - Python "class": they are all inferior to a jit
25
- - No `**kwargs`
26
- - and just a few dozen-jillion other things.
27
-
28
- """
29
- # print("babbage")
30
- countInitialize(connectionGraph=connectionGraph, gapsWhere=gapsWhere, my=my, the=the, track=track)
31
-
32
- if the[indexThe.taskDivisions.value] > 0:
33
- countParallel(connectionGraph=connectionGraph, foldsSubTotals=foldsSubTotals, gapsWherePARALLEL=gapsWhere, myPARALLEL=my, the=the, trackPARALLEL=track)
34
- else:
35
- countSequential(connectionGraph=connectionGraph, foldsSubTotals=foldsSubTotals, gapsWhere=gapsWhere, my=my, the=the, track=track)
mapFolding/beDRY.py DELETED
@@ -1,325 +0,0 @@
1
- """A relatively stable API for oft-needed functionality."""
2
- from mapFolding import dtypeDefault, dtypeLarge, pathJobDEFAULT
3
- from mapFolding import indexMy, indexThe, indexTrack, computationState
4
- from mapFolding import intInnit, defineConcurrencyLimit, oopsieKwargsie
5
- from numpy import integer
6
- from numpy.typing import NDArray
7
- from typing import Any, List, Optional, Sequence, Type, Union
8
- import numba
9
- import numpy
10
- import os
11
- import pathlib
12
- import sys
13
-
14
- def getFilenameFoldsTotal(listDimensions: Sequence[int]) -> str:
15
- return str(sorted(listDimensions)).replace(', ', 'x') + '.foldsTotal'
16
-
17
- def getLeavesTotal(listDimensions: Sequence[int]) -> int:
18
- """
19
- How many leaves are in the map.
20
-
21
- Parameters:
22
- listDimensions: A list of integers representing dimensions.
23
-
24
- Returns:
25
- productDimensions: The product of all positive integer dimensions.
26
- """
27
- listNonNegative = parseDimensions(listDimensions, 'listDimensions')
28
- listPositive = [dimension for dimension in listNonNegative if dimension > 0]
29
-
30
- if not listPositive:
31
- return 0
32
- else:
33
- productDimensions = 1
34
- for dimension in listPositive:
35
- if dimension > sys.maxsize // productDimensions:
36
- raise OverflowError(f"I received {dimension=} in {listDimensions=}, but the product of the dimensions exceeds the maximum size of an integer on this system.")
37
- productDimensions *= dimension
38
-
39
- return productDimensions
40
-
41
- def getPathFilenameFoldsTotal(listDimensions: Sequence[int], pathishWriteFoldsTotal: Optional[Union[str, os.PathLike[str]]] = None) -> pathlib.Path:
42
- pathFilenameFoldsTotal = pathlib.Path(pathishWriteFoldsTotal) if pathishWriteFoldsTotal is not None else pathJobDEFAULT
43
- if pathFilenameFoldsTotal.is_dir():
44
- filenameFoldsTotalDEFAULT = getFilenameFoldsTotal(listDimensions)
45
- pathFilenameFoldsTotal = pathFilenameFoldsTotal / filenameFoldsTotalDEFAULT
46
- pathFilenameFoldsTotal.parent.mkdir(parents=True, exist_ok=True)
47
- return pathFilenameFoldsTotal
48
-
49
- def getTaskDivisions(computationDivisions: Optional[Union[int, str]], concurrencyLimit: int, CPUlimit: Optional[Union[bool, float, int]], listDimensions: Sequence[int]):
50
- """
51
- Determines whether or how to divide the computation into tasks.
52
-
53
- Parameters
54
- ----------
55
- computationDivisions (None):
56
- Specifies how to divide computations:
57
- - None: no division of the computation into tasks; sets task divisions to 0
58
- - int: direct set the number of task divisions; cannot exceed the map's total leaves
59
- - "maximum": divides into `leavesTotal`-many `taskDivisions`
60
- - "cpu": limits the divisions to the number of available CPUs, i.e. `concurrencyLimit`
61
- concurrencyLimit:
62
- Maximum number of concurrent tasks allowed
63
- listDimensions: for error reporting
64
- CPUlimit: for error reporting
65
-
66
- Returns
67
- -------
68
- taskDivisions:
69
-
70
- Raises
71
- ------
72
- ValueError
73
- If computationDivisions is an unsupported type or if resulting task divisions exceed total leaves
74
-
75
- Notes
76
- -----
77
- Task divisions cannot exceed total leaves to prevent duplicate counting of folds.
78
- """
79
- if not computationDivisions:
80
- return 0
81
- else:
82
- leavesTotal = getLeavesTotal(listDimensions)
83
- if isinstance(computationDivisions, int):
84
- taskDivisions = computationDivisions
85
- elif isinstance(computationDivisions, str):
86
- computationDivisions = computationDivisions.lower()
87
- if computationDivisions == "maximum":
88
- taskDivisions = leavesTotal
89
- elif computationDivisions == "cpu":
90
- taskDivisions = min(concurrencyLimit, leavesTotal)
91
- else:
92
- raise ValueError(f"I received {computationDivisions} for the parameter, `computationDivisions`, but the so-called programmer didn't implement code for that.")
93
-
94
- if taskDivisions > leavesTotal:
95
- 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.")
96
-
97
- return taskDivisions
98
-
99
- def makeConnectionGraph(listDimensions: Sequence[int], **keywordArguments: Optional[Type]) -> NDArray[integer[Any]]:
100
- """
101
- Constructs a multi-dimensional connection graph representing the connections between the leaves of a map with the given dimensions.
102
- Also called a Cartesian product decomposition or dimensional product mapping.
103
-
104
- Parameters:
105
- listDimensions: A sequence of integers representing the dimensions of the map.
106
- Returns:
107
- connectionGraph: A 3D numpy array with shape of (dimensionsTotal + 1, leavesTotal + 1, leavesTotal + 1).
108
- """
109
- datatype = keywordArguments.get('datatype', dtypeDefault)
110
- mapShape = validateListDimensions(listDimensions)
111
- leavesTotal = getLeavesTotal(mapShape)
112
- arrayDimensions = numpy.array(mapShape, dtype=datatype)
113
- dimensionsTotal = len(arrayDimensions)
114
-
115
- # Step 1: find the cumulative product of the map's dimensions
116
- cumulativeProduct = numpy.multiply.accumulate([1] + mapShape, dtype=datatype)
117
-
118
- # Step 2: create a coordinate system
119
- coordinateSystem = numpy.zeros((dimensionsTotal + 1, leavesTotal + 1), dtype=datatype)
120
-
121
- for dimension1ndex in range(1, dimensionsTotal + 1):
122
- for leaf1ndex in range(1, leavesTotal + 1):
123
- coordinateSystem[dimension1ndex, leaf1ndex] = (
124
- ((leaf1ndex - 1) // cumulativeProduct[dimension1ndex - 1]) %
125
- arrayDimensions[dimension1ndex - 1] + 1
126
- )
127
-
128
- # Step 3: create and fill the connection graph
129
- connectionGraph = numpy.zeros((dimensionsTotal + 1, leavesTotal + 1, leavesTotal + 1), dtype=datatype)
130
-
131
- for dimension1ndex in range(1, dimensionsTotal + 1):
132
- for activeLeaf1ndex in range(1, leavesTotal + 1):
133
- for connectee1ndex in range(1, activeLeaf1ndex + 1):
134
- # Base coordinate conditions
135
- isFirstCoord = coordinateSystem[dimension1ndex, connectee1ndex] == 1
136
- isLastCoord = coordinateSystem[dimension1ndex, connectee1ndex] == arrayDimensions[dimension1ndex - 1]
137
- exceedsActive = connectee1ndex + cumulativeProduct[dimension1ndex - 1] > activeLeaf1ndex
138
-
139
- # Parity check
140
- isEvenParity = (coordinateSystem[dimension1ndex, activeLeaf1ndex] & 1) == \
141
- (coordinateSystem[dimension1ndex, connectee1ndex] & 1)
142
-
143
- # Determine connection value
144
- if (isEvenParity and isFirstCoord) or (not isEvenParity and (isLastCoord or exceedsActive)):
145
- connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex
146
- elif isEvenParity and not isFirstCoord:
147
- connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex - cumulativeProduct[dimension1ndex - 1]
148
- elif not isEvenParity and not (isLastCoord or exceedsActive):
149
- connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex + cumulativeProduct[dimension1ndex - 1]
150
- else:
151
- connectionGraph[dimension1ndex, activeLeaf1ndex, connectee1ndex] = connectee1ndex
152
-
153
- return connectionGraph
154
-
155
- def makeDataContainer(shape, datatype: Optional[Type] = None):
156
- """Create a container, probably numpy.ndarray, with the given shape and datatype."""
157
- if datatype is None:
158
- datatype = dtypeDefault
159
- return numpy.zeros(shape, dtype=datatype)
160
-
161
- def outfitCountFolds(listDimensions: Sequence[int], computationDivisions: Optional[Union[int, str]] = None, CPUlimit: Optional[Union[bool, float, int]] = None, **keywordArguments: Optional[Type[Any]]) -> computationState:
162
- """
163
- Initializes and configures the computation state for map folding computations.
164
-
165
- Parameters
166
- ----------
167
- listDimensions:
168
- The dimensions of the map to be folded
169
- computationDivisions (None):
170
- Specifies how to divide computations:
171
- - None: no division of the computation into tasks; sets task divisions to 0
172
- - int: direct set the number of task divisions; cannot exceed the map's total leaves
173
- - "maximum": divides into `leavesTotal`-many `taskDivisions`
174
- - "cpu": limits the divisions to the number of available CPUs, i.e. `concurrencyLimit`
175
- CPUlimit (None):
176
- Whether and how to limit the CPU usage. See notes for details.
177
-
178
- Returns
179
- -------
180
- computationState
181
- An initialized computation state containing:
182
- - connectionGraph: Graph representing connections in the map
183
- - foldsSubTotals: Array tracking total folds
184
- - mapShape: Validated and sorted dimensions of the map
185
- - my: Array for internal state tracking
186
- - gapsWhere: Array tracking gap positions
187
- - the: Static settings and metadata
188
- - track: Array for tracking computation progress
189
-
190
- Limits on CPU usage `CPUlimit`:
191
- - `False`, `None`, or `0`: No limits on CPU usage; uses all available CPUs. All other values will potentially limit CPU usage.
192
- - `True`: Yes, limit the CPU usage; limits to 1 CPU.
193
- - Integer `>= 1`: Limits usage to the specified number of CPUs.
194
- - Decimal value (`float`) between 0 and 1: Fraction of total CPUs to use.
195
- - Decimal value (`float`) between -1 and 0: Fraction of CPUs to *not* use.
196
- - Integer `<= -1`: Subtract the absolute value from total CPUs.
197
- """
198
- datatypeDefault = keywordArguments.get('datatypeDefault', dtypeDefault)
199
- datatypeLarge = keywordArguments.get('datatypeLarge', dtypeLarge)
200
-
201
- the = makeDataContainer(len(indexThe), datatypeDefault)
202
-
203
- mapShape = tuple(sorted(validateListDimensions(listDimensions)))
204
- the[indexThe.leavesTotal] = getLeavesTotal(mapShape)
205
- the[indexThe.dimensionsTotal] = len(mapShape)
206
- concurrencyLimit = setCPUlimit(CPUlimit)
207
- the[indexThe.taskDivisions] = getTaskDivisions(computationDivisions, concurrencyLimit, CPUlimit, listDimensions)
208
-
209
- stateInitialized = computationState(
210
- connectionGraph = makeConnectionGraph(mapShape, datatype=datatypeDefault),
211
- foldsSubTotals = makeDataContainer(the[indexThe.leavesTotal], datatypeLarge),
212
- mapShape = mapShape,
213
- my = makeDataContainer(len(indexMy), datatypeLarge),
214
- gapsWhere = makeDataContainer(int(the[indexThe.leavesTotal]) * int(the[indexThe.leavesTotal]) + 1, datatypeDefault),
215
- the = the,
216
- track = makeDataContainer((len(indexTrack), the[indexThe.leavesTotal] + 1), datatypeLarge)
217
- )
218
-
219
- stateInitialized['my'][indexMy.leaf1ndex.value] = 1
220
-
221
- return stateInitialized
222
-
223
- def parseDimensions(dimensions: Sequence[int], parameterName: str = 'unnamed parameter') -> List[int]:
224
- """
225
- Parse and validate dimensions are non-negative integers.
226
-
227
- Parameters:
228
- dimensions: Sequence of integers representing dimensions
229
- parameterName ('unnamed parameter'): Name of the parameter for error messages. Defaults to 'unnamed parameter'
230
- Returns:
231
- listNonNegative: List of validated non-negative integers
232
- Raises:
233
- ValueError: If any dimension is negative or if the list is empty
234
- TypeError: If any element cannot be converted to integer (raised by intInnit)
235
- """
236
- listValidated = intInnit(dimensions, parameterName)
237
- listNonNegative = []
238
- for dimension in listValidated:
239
- if dimension < 0:
240
- raise ValueError(f"Dimension {dimension} must be non-negative")
241
- listNonNegative.append(dimension)
242
-
243
- return listNonNegative
244
-
245
- import tempfile
246
- import shutil
247
- import logging
248
- import os
249
- def saveFoldsTotal(pathFilename: Union[str, os.PathLike[str]], foldsTotal: int) -> None:
250
- """
251
- Save foldsTotal with multiple fallback mechanisms.
252
-
253
- Parameters:
254
- pathFilename: Target save location
255
- foldsTotal: Critical computed value to save
256
- """
257
- """Thoughts
258
- Everything in a try block
259
- Save it multiple times with multiple packages
260
- no need for context managers, especially because they can cause errors"""
261
- try:
262
- pathFilenameFoldsTotal = pathlib.Path(pathFilename)
263
- pathFilenameFoldsTotal.parent.mkdir(parents=True, exist_ok=True)
264
- pathFilenameFoldsTotal.write_text(str(foldsTotal))
265
- except Exception as ERRORmessage:
266
- try:
267
- print(f"\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n\n{foldsTotal=}\n\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n")
268
- print(ERRORmessage)
269
- print(f"\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n\n{foldsTotal=}\n\nfoldsTotal foldsTotal foldsTotal foldsTotal foldsTotal\n")
270
- randomnessPlanB = (int(str(foldsTotal).strip()[-1]) + 1) * ['YO_']
271
- filenameInfixUnique = ''.join(randomnessPlanB)
272
- import os
273
- pathFilenamePlanB = os.path.join(os.getcwd(), 'foldsTotal' + filenameInfixUnique + '.txt')
274
- open(pathFilenamePlanB, 'w').write(str(foldsTotal))
275
- print(str(pathFilenamePlanB))
276
- except:
277
- print(foldsTotal)
278
-
279
- def setCPUlimit(CPUlimit: Union[bool, float, int, None]) -> int:
280
- """Sets CPU limit for Numba concurrent operations. Note that it can only affect Numba-jitted functions that have not yet been imported.
281
-
282
- Parameters:
283
- CPUlimit: whether and how to limit the CPU usage. See notes for details.
284
- Returns:
285
- concurrencyLimit: The actual concurrency limit that was set
286
- Raises:
287
- TypeError: If CPUlimit is not of the expected types
288
-
289
- Limits on CPU usage `CPUlimit`:
290
- - `False`, `None`, or `0`: No limits on CPU usage; uses all available CPUs. All other values will potentially limit CPU usage.
291
- - `True`: Yes, limit the CPU usage; limits to 1 CPU.
292
- - Integer `>= 1`: Limits usage to the specified number of CPUs.
293
- - Decimal value (`float`) between 0 and 1: Fraction of total CPUs to use.
294
- - Decimal value (`float`) between -1 and 0: Fraction of CPUs to *not* use.
295
- - Integer `<= -1`: Subtract the absolute value from total CPUs.
296
- """
297
- if not (CPUlimit is None or isinstance(CPUlimit, (bool, int, float))):
298
- CPUlimit = oopsieKwargsie(CPUlimit)
299
-
300
- concurrencyLimit = defineConcurrencyLimit(CPUlimit)
301
- numba.set_num_threads(concurrencyLimit)
302
-
303
- return concurrencyLimit
304
-
305
- def validateListDimensions(listDimensions: Sequence[int]) -> List[int]:
306
- """
307
- Validates and sorts a sequence of at least two positive dimensions.
308
-
309
- Parameters:
310
- listDimensions: A sequence of integer dimensions to be validated.
311
-
312
- Returns:
313
- dimensionsValidSorted: A list, with at least two elements, of only positive integers.
314
-
315
- Raises:
316
- ValueError: If the input listDimensions is None.
317
- NotImplementedError: If the resulting list of positive dimensions has fewer than two elements.
318
- """
319
- if not listDimensions:
320
- raise ValueError(f"listDimensions is a required parameter.")
321
- listNonNegative = parseDimensions(listDimensions, 'listDimensions')
322
- dimensionsValid = [dimension for dimension in listNonNegative if dimension > 0]
323
- if len(dimensionsValid) < 2:
324
- 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/.")
325
- return sorted(dimensionsValid)
@@ -1,7 +0,0 @@
1
- from mapFolding.lovelace import countSequential
2
- from mapFolding.lovelace import countParallel
3
- from mapFolding.lovelace import countInitialize
4
-
5
- # from mapFolding.countSequential import countSequential
6
- # from mapFolding.countParallel import countParallel
7
- # from mapFolding.countInitialize import countInitialize