mapFolding 0.12.1__py3-none-any.whl → 0.12.2__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 (34) hide show
  1. mapFolding/__init__.py +42 -18
  2. mapFolding/_theSSOT.py +137 -0
  3. mapFolding/basecamp.py +28 -18
  4. mapFolding/beDRY.py +21 -19
  5. mapFolding/dataBaskets.py +170 -18
  6. mapFolding/datatypes.py +109 -1
  7. mapFolding/filesystemToolkit.py +38 -33
  8. mapFolding/oeis.py +209 -93
  9. mapFolding/someAssemblyRequired/RecipeJob.py +120 -9
  10. mapFolding/someAssemblyRequired/__init__.py +35 -38
  11. mapFolding/someAssemblyRequired/_toolIfThis.py +78 -16
  12. mapFolding/someAssemblyRequired/_toolkitContainers.py +121 -43
  13. mapFolding/someAssemblyRequired/infoBooth.py +37 -2
  14. mapFolding/someAssemblyRequired/makeAllModules.py +712 -0
  15. mapFolding/someAssemblyRequired/makeJobTheorem2Numba.py +102 -39
  16. mapFolding/someAssemblyRequired/toolkitNumba.py +171 -19
  17. mapFolding/someAssemblyRequired/transformationTools.py +84 -40
  18. mapfolding-0.12.2.dist-info/METADATA +167 -0
  19. mapfolding-0.12.2.dist-info/RECORD +53 -0
  20. {mapfolding-0.12.1.dist-info → mapfolding-0.12.2.dist-info}/WHEEL +1 -1
  21. tests/__init__.py +28 -44
  22. tests/conftest.py +66 -61
  23. tests/test_computations.py +39 -82
  24. tests/test_filesystem.py +25 -1
  25. tests/test_oeis.py +30 -1
  26. tests/test_other.py +27 -0
  27. tests/test_tasks.py +31 -1
  28. mapFolding/someAssemblyRequired/Z0Z_makeAllModules.py +0 -433
  29. mapFolding/theSSOT.py +0 -34
  30. mapfolding-0.12.1.dist-info/METADATA +0 -184
  31. mapfolding-0.12.1.dist-info/RECORD +0 -53
  32. {mapfolding-0.12.1.dist-info → mapfolding-0.12.2.dist-info}/entry_points.txt +0 -0
  33. {mapfolding-0.12.1.dist-info → mapfolding-0.12.2.dist-info}/licenses/LICENSE +0 -0
  34. {mapfolding-0.12.1.dist-info → mapfolding-0.12.2.dist-info}/top_level.txt +0 -0
@@ -1,41 +1,71 @@
1
- from mapFolding import getPathFilenameFoldsTotal, MapFoldingState, packageSettings
2
- from mapFolding.someAssemblyRequired import IfThis, raiseIfNoneGitHubIssueNumber3
1
+ """
2
+ Map folding AST transformation system: Specialized job generation and optimization implementation.
3
+
4
+ This module implements the specialized job generation layer of the map folding AST transformation
5
+ system, executing the complete transformation process to convert generic map folding algorithms
6
+ into highly optimized, standalone computation modules. Building upon the configuration orchestration
7
+ established in the recipe system, this module applies the full sequence of transformations from
8
+ pattern recognition through Numba compilation to produce self-contained computational solutions
9
+ optimized for specific map dimensions and calculation contexts.
10
+
11
+ The transformation implementation addresses the computational demands of map folding research where
12
+ calculations can require hours or days to complete. The specialization process converts abstract
13
+ algorithms with flexible parameters into concrete, statically-optimized code that leverages
14
+ just-in-time compilation for maximum performance. Each generated module targets specific map
15
+ shapes and calculation modes, enabling aggressive compiler optimizations based on known constraints
16
+ and embedded constants.
17
+
18
+ The optimization process executes systematic transformations including static value embedding to
19
+ replace parameterized values with compile-time constants, dead code elimination to remove unused
20
+ variables and code paths, parameter internalization to convert function parameters into embedded
21
+ variables, import optimization to replace generic imports with specific implementations, Numba
22
+ decoration with appropriate compilation directives, progress integration for long-running calculations,
23
+ and launcher generation for standalone execution entry points.
24
+
25
+ The resulting modules represent the culmination of the entire AST transformation system, producing
26
+ self-contained Python scripts that execute independently with dramatically improved performance
27
+ compared to original generic algorithms while maintaining mathematical correctness and providing
28
+ essential progress feedback capabilities for large-scale computational research.
29
+ """
30
+
3
31
  from astToolkit import (
4
- Be,
5
- ClassIsAndAttribute,
6
- extractFunctionDef,
7
- IngredientsFunction,
8
- IngredientsModule,
9
- LedgerOfImports,
10
- Make,
11
- NodeChanger,
12
- NodeTourist,
13
- str_nameDOTname,
14
- Then,
32
+ Be, ClassIsAndAttribute, extractFunctionDef, identifierDotAttribute, IngredientsFunction,
33
+ IngredientsModule, LedgerOfImports, Make, NodeChanger, NodeTourist, Then,
15
34
  )
16
35
  from astToolkit.transformationTools import write_astModule
36
+ from mapFolding import getPathFilenameFoldsTotal, MapFoldingState, packageSettings
37
+ from mapFolding.someAssemblyRequired import IfThis
17
38
  from mapFolding.someAssemblyRequired.RecipeJob import RecipeJobTheorem2Numba
18
- from mapFolding.someAssemblyRequired.toolkitNumba import decorateCallableWithNumba, parametersNumbaLight, SpicesJobNumba
39
+ from mapFolding.someAssemblyRequired.toolkitNumba import (
40
+ decorateCallableWithNumba, parametersNumbaLight, SpicesJobNumba,
41
+ )
19
42
  from mapFolding.syntheticModules.initializeCount import initializeGroupsOfFolds
20
43
  from pathlib import PurePosixPath
21
44
  from typing import cast, NamedTuple
22
- from Z0Z_tools import autoDecodingRLE
45
+ from Z0Z_tools import autoDecodingRLE, raiseIfNone
23
46
  import ast
24
- """Synthesize one file to compute `foldsTotal` of `mapShape`."""
25
47
 
26
- listIdentifiersNotUsedAllHARDCODED = ['concurrencyLimit', 'foldsTotal', 'mapShape',]
27
- listIdentifiersNotUsedParallelSequentialHARDCODED = ['indexLeaf']
28
- listIdentifiersNotUsedSequentialHARDCODED = ['foldGroups', 'taskDivisions', 'taskIndex',]
48
+ # Configuration lists for code optimization and dead code elimination
49
+ listIdentifiersNotUsedAllHARDCODED: list[str] = ['concurrencyLimit', 'foldsTotal', 'mapShape',]
50
+ """Identifiers that are universally unused across all optimization contexts."""
51
+
52
+ listIdentifiersNotUsedParallelSequentialHARDCODED: list[str] = ['indexLeaf']
53
+ """Identifiers unused in both parallel and sequential execution modes."""
54
+
55
+ listIdentifiersNotUsedSequentialHARDCODED: list[str] = ['foldGroups', 'taskDivisions', 'taskIndex',]
56
+ """Identifiers unused specifically in sequential execution mode."""
29
57
 
30
- listIdentifiersReplacedHARDCODED = ['groupsOfFolds',]
58
+ listIdentifiersReplacedHARDCODED: list[str] = ['groupsOfFolds',]
59
+ """Identifiers that get replaced with optimized equivalents during transformation."""
31
60
 
32
- listIdentifiersStaticValuesHARDCODED = ['dimensionsTotal', 'leavesTotal',]
61
+ listIdentifiersStaticValuesHARDCODED: list[str] = ['dimensionsTotal', 'leavesTotal',]
62
+ """Identifiers with compile-time constant values that can be embedded directly."""
33
63
 
34
- listIdentifiersNotUsedHARDCODED = listIdentifiersStaticValuesHARDCODED + listIdentifiersReplacedHARDCODED + listIdentifiersNotUsedAllHARDCODED + listIdentifiersNotUsedParallelSequentialHARDCODED + listIdentifiersNotUsedSequentialHARDCODED
64
+ listIdentifiersNotUsedHARDCODED: list[str] = listIdentifiersStaticValuesHARDCODED + listIdentifiersReplacedHARDCODED + listIdentifiersNotUsedAllHARDCODED + listIdentifiersNotUsedParallelSequentialHARDCODED + listIdentifiersNotUsedSequentialHARDCODED
65
+ """Complete list of all identifiers that can be eliminated during optimization."""
35
66
 
36
67
  def addLauncherNumbaProgress(ingredientsModule: IngredientsModule, ingredientsFunction: IngredientsFunction, job: RecipeJobTheorem2Numba, spices: SpicesJobNumba) -> tuple[IngredientsModule, IngredientsFunction]:
37
- """
38
- Add progress tracking capabilities to a Numba-optimized function.
68
+ """Add progress tracking capabilities to a Numba-optimized function.
39
69
 
40
70
  This function modifies both the module and the function to integrate Numba-compatible
41
71
  progress tracking for long-running calculations. It performs several key transformations:
@@ -56,8 +86,9 @@ def addLauncherNumbaProgress(ingredientsModule: IngredientsModule, ingredientsFu
56
86
  spices: Configuration specifying progress bar details.
57
87
 
58
88
  Returns:
59
- A tuple containing the modified module and function with progress tracking.
89
+ Modified module and function with integrated progress tracking capabilities.
60
90
  """
91
+
61
92
  linesLaunch: str = f"""
62
93
  if __name__ == '__main__':
63
94
  with ProgressBar(total={job.foldsTotalEstimated}, update_interval=2) as statusUpdate:
@@ -90,17 +121,16 @@ if __name__ == '__main__':
90
121
  return ingredientsModule, ingredientsFunction
91
122
 
92
123
  def move_arg2FunctionDefDOTbodyAndAssignInitialValues(ingredientsFunction: IngredientsFunction, job: RecipeJobTheorem2Numba) -> IngredientsFunction:
93
- """
94
- Convert function parameters into initialized variables with concrete values.
124
+ """Convert function parameters into initialized variables with concrete values.
95
125
 
96
126
  This function implements a critical transformation that converts function parameters
97
127
  into statically initialized variables in the function body. This enables several
98
128
  optimizations:
99
129
 
100
- 1. Eliminating parameter passing overhead.
101
- 2. Embedding concrete values directly in the code.
102
- 3. Allowing Numba to optimize based on known value characteristics.
103
- 4. Simplifying function signatures for specialized use cases.
130
+ 1. Eliminating parameter passing overhead
131
+ 2. Embedding concrete values directly in the code
132
+ 3. Allowing Numba to optimize based on known value characteristics
133
+ 4. Simplifying function signatures for specialized use cases
104
134
 
105
135
  The function handles different data types (scalars, arrays, custom types) appropriately,
106
136
  replacing abstract parameter references with concrete values from the computation state.
@@ -115,7 +145,7 @@ def move_arg2FunctionDefDOTbodyAndAssignInitialValues(ingredientsFunction: Ingre
115
145
  """
116
146
  ingredientsFunction.imports.update(job.shatteredDataclass.imports)
117
147
 
118
- list_argCuzMyBrainRefusesToThink = ingredientsFunction.astFunctionDef.args.args + ingredientsFunction.astFunctionDef.args.posonlyargs + ingredientsFunction.astFunctionDef.args.kwonlyargs
148
+ list_argCuzMyBrainRefusesToThink: list[ast.arg] = ingredientsFunction.astFunctionDef.args.args + ingredientsFunction.astFunctionDef.args.posonlyargs + ingredientsFunction.astFunctionDef.args.kwonlyargs
119
149
  list_arg_arg: list[str] = [ast_arg.arg for ast_arg in list_argCuzMyBrainRefusesToThink]
120
150
  listName: list[ast.Name] = []
121
151
  NodeTourist(Be.Name, Then.appendTo(listName)).visit(ingredientsFunction.astFunctionDef)
@@ -154,9 +184,31 @@ def move_arg2FunctionDefDOTbodyAndAssignInitialValues(ingredientsFunction: Ingre
154
184
  return ingredientsFunction
155
185
 
156
186
  def makeJobNumba(job: RecipeJobTheorem2Numba, spices: SpicesJobNumba) -> None:
187
+ """Generate an optimized Numba-compiled computation module for map folding calculations.
188
+
189
+ This function orchestrates the complete code transformation pipeline to convert
190
+ a generic map folding algorithm into a highly optimized, specialized computation
191
+ module. The transformation process includes:
192
+
193
+ 1. Extract and modify the source function from the generic algorithm
194
+ 2. Replace static-valued identifiers with their concrete values
195
+ 3. Convert function parameters to embedded initialized variables
196
+ 4. Remove unused code paths and variables for optimization
197
+ 5. Configure appropriate Numba decorators for JIT compilation
198
+ 6. Add progress tracking capabilities for long-running computations
199
+ 7. Generate standalone launcher code for direct execution
200
+ 8. Write the complete optimized module to the filesystem
157
201
 
158
- astFunctionDef = extractFunctionDef(job.source_astModule, job.countCallable)
159
- if not astFunctionDef: raise raiseIfNoneGitHubIssueNumber3
202
+ The resulting module is a self-contained Python script that can execute
203
+ map folding calculations for the specific map dimensions with maximum
204
+ performance through just-in-time compilation.
205
+
206
+ Parameters:
207
+ job: Configuration recipe containing source locations, target paths, and state.
208
+ spices: Optimization settings including Numba parameters and progress options.
209
+ """
210
+
211
+ astFunctionDef: ast.FunctionDef = raiseIfNone(extractFunctionDef(job.source_astModule, job.countCallable))
160
212
  ingredientsCount: IngredientsFunction = IngredientsFunction(astFunctionDef, LedgerOfImports())
161
213
 
162
214
  # Remove `foldGroups` and any other unused statements, so you can dynamically determine which variables are not used
@@ -167,7 +219,7 @@ def makeJobNumba(job: RecipeJobTheorem2Numba, spices: SpicesJobNumba) -> None:
167
219
  # remove_foldGroups.visit(ingredientsCount.astFunctionDef)
168
220
 
169
221
  # replace identifiers with static values with their values, so you can dynamically determine which variables are not used
170
- listIdentifiersStaticValues = listIdentifiersStaticValuesHARDCODED
222
+ listIdentifiersStaticValues: list[str] = listIdentifiersStaticValuesHARDCODED
171
223
  for identifier in listIdentifiersStaticValues:
172
224
  findThis = IfThis.isNameIdentifier(identifier)
173
225
  doThat = Then.replaceWith(Make.Constant(int(job.state.__dict__[identifier])))
@@ -198,14 +250,26 @@ if __name__ == '__main__':
198
250
  ingredientsCount.astFunctionDef.returns = job.shatteredDataclass.countingVariableAnnotation
199
251
 
200
252
  ingredientsCount = move_arg2FunctionDefDOTbodyAndAssignInitialValues(ingredientsCount, job)
201
-
202
253
  class DatatypeConfig(NamedTuple):
203
- Z0Z_module: str_nameDOTname
254
+ """Configuration for mapping framework datatypes to Numba-compatible types.
255
+
256
+ This configuration class defines how abstract datatypes used in the map folding
257
+ framework should be replaced with concrete Numba-compatible types during code
258
+ generation. Each configuration specifies the source module, target type name,
259
+ and optional import alias for the transformation.
260
+
261
+ Attributes:
262
+ fml: Framework datatype identifier to be replaced.
263
+ Z0Z_module: Module containing the target datatype (e.g., 'numba', 'numpy').
264
+ Z0Z_type_name: Concrete type name in the target module.
265
+ Z0Z_asname: Optional import alias for the type.
266
+ """
204
267
  fml: str
268
+ Z0Z_module: identifierDotAttribute
205
269
  Z0Z_type_name: str
206
270
  Z0Z_asname: str | None = None
207
271
 
208
- listDatatypeConfigs = [
272
+ listDatatypeConfigs: list[DatatypeConfig] = [
209
273
  DatatypeConfig(fml='DatatypeLeavesTotal', Z0Z_module='numba', Z0Z_type_name='uint8'),
210
274
  DatatypeConfig(fml='DatatypeElephino', Z0Z_module='numba', Z0Z_type_name='uint16'),
211
275
  DatatypeConfig(fml='DatatypeFoldsTotal', Z0Z_module='numba', Z0Z_type_name='uint64'),
@@ -234,7 +298,6 @@ if __name__ == '__main__':
234
298
  ingredientsCount.astFunctionDef.decorator_list = [] # TODO low-priority, handle this more elegantly
235
299
  # TODO when I add the function signature in numba style back to the decorator, the logic needs to handle `ProgressBarType:`
236
300
  ingredientsCount = decorateCallableWithNumba(ingredientsCount, spices.parametersNumba)
237
-
238
301
  ingredientsModule.appendIngredientsFunction(ingredientsCount)
239
302
  write_astModule(ingredientsModule, job.pathFilenameModule, job.packageIdentifier)
240
303
 
@@ -1,30 +1,61 @@
1
1
  """
2
- Numba-specific Tools for Generating Optimized Code
2
+ Map folding AST transformation system: Numba integration and just-in-time compilation optimization.
3
3
 
4
- This module provides specialized tools for transforming standard Python code into
5
- Numba-accelerated implementations. It implements a comprehensive transformation
6
- assembly-line that:
4
+ This module provides the compilation optimization layer of the map folding AST transformation system,
5
+ implementing comprehensive tools for applying Numba's just-in-time compilation to functions generated
6
+ by the core transformation tools. Building upon the dataclass decomposition and function optimization
7
+ capabilities established in the operational core, this module completes the transformation process
8
+ by applying aggressive performance optimizations through strategic compiler configuration.
7
9
 
8
- 1. Converts dataclass-based algorithm implementations into Numba-compatible versions.
9
- 2. Applies appropriate Numba decorators with optimized configuration settings.
10
- 3. Restructures code to work within Numba's constraints.
11
- 4. Manages type information for optimized compilation.
10
+ The integration addresses the final stage of the transformation process where decomposed, optimized
11
+ functions receive Numba decorators with carefully configured optimization parameters. The module
12
+ handles the complexities of type signature generation, import management, and decorator conflict
13
+ resolution that arise when converting high-level map folding algorithms into machine-optimized code.
12
14
 
13
- The module bridges the gap between readable, maintainable Python code and
14
- highly-optimized numerical computing implementations, enabling significant
15
- performance improvements while preserving code semantics and correctness.
15
+ Two primary compilation strategies accommodate different performance and compatibility requirements:
16
+ aggressive optimization for production numerical computing provides maximum performance through
17
+ comprehensive compiler directives including nopython mode, bounds checking elimination, forced
18
+ function inlining, and fastmath optimizations; lightweight optimization maintains broader compatibility
19
+ while achieving significant performance gains through selective compiler optimizations suitable for
20
+ development and testing environments.
21
+
22
+ The strategic application of these optimization configurations enables map folding calculations that
23
+ require hours or days to complete, transforming abstract mathematical algorithms into highly efficient
24
+ computational modules. The compilation layer integrates seamlessly with the broader transformation
25
+ system to produce standalone modules optimized for specific map dimensions and computational contexts.
16
26
  """
17
27
 
28
+ from astToolkit import identifierDotAttribute, IngredientsFunction, Make
18
29
  from collections.abc import Callable, Sequence
19
- from mapFolding import NotRequired, TypedDict
20
- from astToolkit import IngredientsFunction, Make, str_nameDOTname
21
- from astToolkit.transformationTools import write_astModule
22
30
  from numba.core.compiler import CompilerBase as numbaCompilerBase
23
- from typing import Any, cast, Final
31
+ from typing import Any, cast, Final, NotRequired, TypedDict
24
32
  import ast
25
33
  import dataclasses
34
+ import warnings
26
35
 
27
36
  class ParametersNumba(TypedDict):
37
+ """
38
+ Configuration parameters for Numba compilation decorators.
39
+
40
+ This TypedDict defines all possible configuration options that can be passed to Numba's
41
+ `@jit` decorator to control compilation behavior. The parameters enable fine-tuned control
42
+ over optimization strategies, debugging features, and runtime behavior.
43
+
44
+ Key compilation modes:
45
+ nopython: Forces compilation without Python fallback for maximum performance
46
+ cache: Enables compilation result caching to disk for faster subsequent runs
47
+ fastmath: Allows aggressive mathematical optimizations at cost of IEEE compliance
48
+ parallel: Enables automatic parallelization of supported operations
49
+
50
+ Debug and development options:
51
+ debug: Enables debug information generation
52
+ boundscheck: Controls array bounds checking (disabled for performance in production)
53
+ error_model: Defines how numerical errors are handled ('numpy' vs 'python')
54
+
55
+ Only `cache`, `error_model`, and `fastmath` are required fields. All other fields are
56
+ optional via `NotRequired`, allowing flexible configuration while requiring explicit
57
+ decisions on critical performance and correctness parameters.
58
+ """
28
59
  _dbg_extend_lifetimes: NotRequired[bool]
29
60
  _dbg_optnone: NotRequired[bool]
30
61
  _nrt: NotRequired[bool]
@@ -49,22 +80,121 @@ class ParametersNumba(TypedDict):
49
80
  target: NotRequired[str]
50
81
 
51
82
  parametersNumbaDefault: Final[ParametersNumba] = { '_nrt': True, 'boundscheck': False, 'cache': True, 'error_model': 'numpy', 'fastmath': True, 'forceinline': True, 'inline': 'always', 'looplift': False, 'no_cfunc_wrapper': False, 'no_cpython_wrapper': False, 'nopython': True, 'parallel': False, }
52
- """Middle of the road: fast, lean, but will talk to non-jitted functions."""
83
+ """
84
+ Comprehensive Numba configuration for maximum performance optimization.
85
+
86
+ This configuration provides aggressive optimization settings suitable for production
87
+ numerical computing code. Key characteristics:
88
+ Enables nopython mode for full compilation without Python fallback
89
+ Disables bounds checking for maximum array access performance
90
+ Forces function inlining with 'always' policy for reduced call overhead
91
+ Uses numpy error model for consistent numerical behavior
92
+ Enables fastmath for aggressive floating-point optimizations
93
+ Disables loop lifting to prevent unexpected performance penalties
94
+
95
+ The configuration prioritizes execution speed over compatibility, producing highly
96
+ optimized machine code at the cost of reduced interoperability with uncompiled
97
+ Python functions.
98
+ """
99
+
53
100
  parametersNumbaLight: Final[ParametersNumba] = {'cache': True, 'error_model': 'numpy', 'fastmath': True, 'forceinline': True}
101
+ """
102
+ Minimal Numba configuration for basic optimization with maximum compatibility.
103
+
104
+ This lightweight configuration provides essential optimizations while maintaining
105
+ broad compatibility with existing Python code. Suitable for:
106
+ Development and debugging phases
107
+ Code that needs to interoperate with non-Numba functions
108
+ Situations where full nopython mode causes compilation issues
109
+
110
+ Key features:
111
+ Enables compilation caching for faster subsequent runs
112
+ Uses numpy error model for consistent mathematical behavior
113
+ Enables fastmath and function inlining for performance gains
114
+ Allows Python object mode fallback when needed
115
+ """
116
+
117
+ Z0Z_numbaDataTypeModule: identifierDotAttribute = 'numba'
118
+ """
119
+ Module identifier for Numba imports and type annotations.
120
+
121
+ This constant specifies the module path used when importing Numba-specific types and decorators
122
+ in generated code. It serves as the single source of truth for the Numba module reference,
123
+ enabling consistent import statements across all generated functions.
124
+ """
54
125
 
55
- Z0Z_numbaDataTypeModule: str_nameDOTname = 'numba'
56
126
  Z0Z_decoratorCallable: str = 'jit'
127
+ """
128
+ The Numba decorator function name used for just-in-time compilation.
129
+
130
+ This constant identifies the specific Numba decorator applied to functions for compilation.
131
+ While Numba offers multiple decorators (`@jit`, `@njit`, `@vectorize`), this toolkit focuses
132
+ on the general-purpose `@jit` decorator with configurable parameters for flexibility.
133
+ """
57
134
 
58
135
  def decorateCallableWithNumba(ingredientsFunction: IngredientsFunction, parametersNumba: ParametersNumba | None = None) -> IngredientsFunction:
136
+ """
137
+ Transform a Python function into a Numba-accelerated version with appropriate decorators.
138
+
139
+ This function applies Numba's @jit decorator to an existing function definition within
140
+ an IngredientsFunction container. It handles the complete transformation pipeline:
141
+
142
+ 1. Removes any existing decorators that might conflict with Numba
143
+ 2. Constructs type signatures for Numba compilation when possible
144
+ 3. Applies the @jit decorator with specified or default parameters
145
+ 4. Updates import requirements to include necessary Numba modules
146
+
147
+ The transformation preserves function semantics while enabling significant performance
148
+ improvements through just-in-time compilation. Type inference is attempted for
149
+ function parameters and return values to enable optimized compilation paths.
150
+ Parameters:
151
+ ingredientsFunction: Container holding the function definition and associated metadata
152
+ parametersNumba: Optional Numba configuration; uses parametersNumbaDefault if None
153
+ Returns:
154
+ Modified IngredientsFunction with Numba decorator applied and imports updated
155
+ """
59
156
  def Z0Z_UnhandledDecorators(astCallable: ast.FunctionDef) -> ast.FunctionDef:
157
+ """
158
+ Remove existing decorators from function definition to prevent conflicts with Numba.
159
+
160
+ Numba compilation can be incompatible with certain Python decorators, so this
161
+ function strips all existing decorators from a function definition before
162
+ applying the Numba @jit decorator. Removed decorators are logged as warnings
163
+ for debugging purposes.
164
+
165
+ TODO: Implement more sophisticated decorator handling that can preserve
166
+ compatible decorators and intelligently handle decorator composition.
167
+
168
+ Parameters:
169
+ astCallable: Function definition AST node to process
170
+
171
+ Returns:
172
+ astCallable: Function definition with decorator list cleared
173
+ """
60
174
  # TODO: more explicit handling of decorators. I'm able to ignore this because I know `algorithmSource` doesn't have any decorators.
61
175
  for decoratorItem in astCallable.decorator_list.copy():
62
- import warnings
63
176
  astCallable.decorator_list.remove(decoratorItem)
64
177
  warnings.warn(f"Removed decorator {ast.unparse(decoratorItem)} from {astCallable.name}")
65
178
  return astCallable
66
179
 
67
180
  def makeSpecialSignatureForNumba(signatureElement: ast.arg) -> ast.Subscript | ast.Name | None: # pyright: ignore[reportUnusedFunction]
181
+ """
182
+ Generate Numba-compatible type signatures for function parameters.
183
+
184
+ This function analyzes function parameter type annotations and converts them into
185
+ Numba-compatible type signature expressions. It handles various annotation patterns
186
+ including array types with shape and dtype information, scalar types with simple
187
+ name annotations, and complex subscripted types requiring special handling.
188
+
189
+ The generated signatures enable Numba to perform more efficient compilation by
190
+ providing explicit type information rather than relying solely on type inference.
191
+
192
+ Parameters:
193
+ signatureElement: Function parameter with type annotation to convert
194
+
195
+ Returns:
196
+ Numba-compatible type signature AST node, or None if conversion not possible
197
+ """
68
198
  if isinstance(signatureElement.annotation, ast.Subscript) and isinstance(signatureElement.annotation.slice, ast.Tuple):
69
199
  annotationShape: ast.expr = signatureElement.annotation.slice.elts[0]
70
200
  if isinstance(annotationShape, ast.Subscript) and isinstance(annotationShape.slice, ast.Tuple):
@@ -113,7 +243,7 @@ def decorateCallableWithNumba(ingredientsFunction: IngredientsFunction, paramete
113
243
  ingredientsFunction.astFunctionDef = Z0Z_UnhandledDecorators(ingredientsFunction.astFunctionDef)
114
244
  if parametersNumba is None:
115
245
  parametersNumba = parametersNumbaDefault
116
- listDecoratorKeywords: list[ast.keyword] = [Make.keyword(parameterName, Make.Constant(parameterValue)) for parameterName, parameterValue in parametersNumba.items()]
246
+ listDecoratorKeywords: list[ast.keyword] = [Make.keyword(parameterName, Make.Constant(parameterValue)) for parameterName, parameterValue in parametersNumba.items()] # pyright: ignore[reportArgumentType]
117
247
 
118
248
  decoratorModule = Z0Z_numbaDataTypeModule
119
249
  decoratorCallable = Z0Z_decoratorCallable
@@ -127,6 +257,28 @@ def decorateCallableWithNumba(ingredientsFunction: IngredientsFunction, paramete
127
257
 
128
258
  @dataclasses.dataclass
129
259
  class SpicesJobNumba:
260
+ """
261
+ Configuration container for Numba-specific job processing options.
262
+
263
+ This dataclass encapsulates configuration settings that control how Numba
264
+ compilation and execution is applied to job processing functions. It provides
265
+ a centralized way to manage Numba-specific settings that affect both
266
+ compilation behavior and runtime features like progress reporting.
267
+
268
+ The class serves as a bridge between the generic job processing system and
269
+ Numba's specialized requirements, enabling consistent application of
270
+ optimization settings across different computational contexts.
271
+
272
+ Attributes:
273
+ useNumbaProgressBar: Enable progress bar display for long-running computations
274
+ numbaProgressBarIdentifier: Progress bar implementation identifier
275
+ parametersNumba: Numba compilation parameters with sensible defaults
276
+ """
130
277
  useNumbaProgressBar: bool = True
278
+ """Enable progress bar display for Numba-compiled functions with long execution times."""
279
+
131
280
  numbaProgressBarIdentifier: str = 'ProgressBarGroupsOfFolds'
281
+ """Identifier for the progress bar implementation used in Numba-compiled code."""
282
+
132
283
  parametersNumba: ParametersNumba = dataclasses.field(default_factory=ParametersNumba) # pyright: ignore[reportArgumentType, reportCallIssue, reportUnknownVariableType]
284
+ """Numba compilation parameters; defaults to empty dict allowing decorator defaults."""
@@ -1,45 +1,42 @@
1
1
  """
2
- AST Transformation Tools for Python Code Generation
3
-
4
- This module provides tools for manipulating and transforming Python abstract syntax trees
5
- to generate optimized code. It implements a system that:
6
-
7
- 1. Extracts functions and classes from existing modules.
8
- 2. Reshapes and transforms them through AST manipulation.
9
- 3. Manages dependencies and imports.
10
- 4. Generates optimized code with specialized implementations.
11
-
12
- The module is particularly focused on transforming general-purpose Python code into
13
- high-performance implementations, especially through dataclass decomposition and
14
- function inlining for Numba compatibility.
15
-
16
- At its core, the module implements a transformation assembly-line where code flows from
17
- readable, maintainable implementations to highly optimized versions while preserving
18
- logical structure and correctness.
2
+ Map folding AST transformation system: Core dataclass decomposition and function optimization tools.
3
+
4
+ This module implements the essential transformation capabilities that form the operational core of
5
+ the map folding AST transformation system. Working with the pattern recognition foundation and
6
+ decomposition containers established in the foundational layers, these tools execute the critical
7
+ transformations that convert dataclass-based functions into optimized implementations suitable
8
+ for Numba just-in-time compilation.
9
+
10
+ The transformation process addresses the fundamental incompatibility between dataclass-dependent
11
+ map folding algorithms and Numba's compilation requirements. While dataclass instances provide
12
+ clean, maintainable interfaces for complex mathematical state, Numba cannot directly process
13
+ these objects but excels at optimizing operations on primitive values and tuples. The tools
14
+ bridge this architectural gap through systematic function signature transformation and calling
15
+ convention adaptation.
16
+
17
+ The three-stage transformation pattern implemented here follows a precise sequence: dataclass
18
+ decomposition breaks down dataclass definitions into constituent AST components while extracting
19
+ field definitions and type annotations; function transformation converts functions accepting
20
+ dataclass parameters to functions accepting individual field parameters with updated signatures
21
+ and return types; caller adaptation modifies calling code to unpack dataclass instances, invoke
22
+ transformed functions, and repack results back into dataclass instances.
23
+
24
+ This approach enables seamless integration between high-level dataclass-based interfaces and
25
+ low-level optimized implementations, maintaining code clarity while achieving performance gains
26
+ through specialized compilation paths essential for computationally intensive map folding research.
19
27
  """
20
28
 
21
- from astToolkit import ClassIsAndAttribute
22
- from mapFolding.someAssemblyRequired import (
23
- DeReConstructField2ast,
24
- IfThis,
25
- ShatteredDataclass,
26
- )
27
- from astToolkit import(
28
- Be,
29
- extractClassDef,
30
- IngredientsFunction,
31
- Make,
32
- NodeChanger,
33
- parseLogicalPath2astModule,
34
- str_nameDOTname,
35
- Then,
29
+ from astToolkit import (
30
+ Be, ClassIsAndAttribute, extractClassDef, identifierDotAttribute, IngredientsFunction, Make,
31
+ NodeChanger, parseLogicalPath2astModule, Then,
36
32
  )
37
33
  from astToolkit.transformationTools import unparseFindReplace
34
+ from mapFolding.someAssemblyRequired import DeReConstructField2ast, IfThis, ShatteredDataclass
38
35
  from Z0Z_tools import importLogicalPath2Callable
39
36
  import ast
40
37
  import dataclasses
41
38
 
42
- def shatter_dataclassesDOTdataclass(logicalPathModule: str_nameDOTname, dataclassIdentifier: str, instanceIdentifier: str) -> ShatteredDataclass:
39
+ def shatter_dataclassesDOTdataclass(logicalPathModule: identifierDotAttribute, dataclassIdentifier: str, instanceIdentifier: str) -> ShatteredDataclass:
43
40
  """
44
41
  Decompose a dataclass definition into AST components for manipulation and code generation.
45
42
 
@@ -72,8 +69,9 @@ def shatter_dataclassesDOTdataclass(logicalPathModule: str_nameDOTname, dataclas
72
69
  Official_fieldOrder: list[str] = []
73
70
  dictionaryDeReConstruction: dict[str, DeReConstructField2ast] = {}
74
71
 
75
- dataclassClassDef = extractClassDef(parseLogicalPath2astModule(logicalPathModule), dataclassIdentifier)
76
- if not isinstance(dataclassClassDef, ast.ClassDef): raise ValueError(f"I could not find `{dataclassIdentifier = }` in `{logicalPathModule = }`.")
72
+ dataclassClassDef: ast.ClassDef | None = extractClassDef(parseLogicalPath2astModule(logicalPathModule), dataclassIdentifier)
73
+ if not isinstance(dataclassClassDef, ast.ClassDef):
74
+ raise ValueError(f"I could not find `{dataclassIdentifier = }` in `{logicalPathModule = }`.")
77
75
 
78
76
  countingVariable = None
79
77
  for aField in dataclasses.fields(importLogicalPath2Callable(logicalPathModule, dataclassIdentifier)): # pyright: ignore [reportArgumentType]
@@ -81,11 +79,10 @@ def shatter_dataclassesDOTdataclass(logicalPathModule: str_nameDOTname, dataclas
81
79
  dictionaryDeReConstruction[aField.name] = DeReConstructField2ast(logicalPathModule, dataclassClassDef, instanceIdentifier, aField)
82
80
  if aField.metadata.get('theCountingIdentifier', False):
83
81
  countingVariable = dictionaryDeReConstruction[aField.name].name
84
-
85
82
  if countingVariable is None:
86
- import warnings
87
- warnings.warn(message=f"I could not find the counting variable in `{dataclassIdentifier = }` in `{logicalPathModule = }`.", category=UserWarning)
88
- raise Exception
83
+ # import warnings
84
+ # warnings.warn(message=f"I could not find the counting variable in `{dataclassIdentifier = }` in `{logicalPathModule = }`.", category=UserWarning)
85
+ raise ValueError(f"I could not find the counting variable in `{dataclassIdentifier = }` in `{logicalPathModule = }`.")
89
86
 
90
87
  shatteredDataclass = ShatteredDataclass(
91
88
  countingVariableAnnotation=dictionaryDeReConstruction[countingVariable].astAnnotation,
@@ -109,7 +106,29 @@ def shatter_dataclassesDOTdataclass(logicalPathModule: str_nameDOTname, dataclas
109
106
  return shatteredDataclass
110
107
 
111
108
  def removeDataclassFromFunction(ingredientsTarget: IngredientsFunction, shatteredDataclass: ShatteredDataclass) -> IngredientsFunction:
112
- ingredientsTarget.astFunctionDef.args = Make.arguments(args=shatteredDataclass.list_argAnnotated4ArgumentsSpecification)
109
+ """
110
+ Transform a function that operates on dataclass instances to work with individual field parameters.
111
+
112
+ This function performs the core transformation required for Numba compatibility by removing dataclass
113
+ dependencies from function signatures and implementations. It modifies the target function to:
114
+
115
+ 1. Replace the single dataclass parameter with individual field parameters.
116
+ 2. Update the return type annotation to return a tuple of field values.
117
+ 3. Transform return statements to return the tuple of fields.
118
+ 4. Replace all dataclass attribute access with direct field variable access.
119
+
120
+ This transformation is essential for creating Numba-compatible functions from dataclass-based
121
+ implementations, as Numba cannot handle dataclass instances directly but can efficiently
122
+ process individual primitive values and tuples.
123
+
124
+ Parameters:
125
+ ingredientsTarget: The function definition and its dependencies to be transformed.
126
+ shatteredDataclass: The decomposed dataclass components providing AST mappings and transformations.
127
+
128
+ Returns:
129
+ ingredientsTarget: The modified function ingredients with dataclass dependencies removed.
130
+ """
131
+ ingredientsTarget.astFunctionDef.args = Make.arguments(list_arg=shatteredDataclass.list_argAnnotated4ArgumentsSpecification)
113
132
  ingredientsTarget.astFunctionDef.returns = shatteredDataclass.signatureReturnAnnotation
114
133
  changeReturnCallable = NodeChanger(Be.Return, Then.replaceWith(Make.Return(shatteredDataclass.fragments4AssignmentOrParameters)))
115
134
  changeReturnCallable.visit(ingredientsTarget.astFunctionDef)
@@ -117,6 +136,31 @@ def removeDataclassFromFunction(ingredientsTarget: IngredientsFunction, shattere
117
136
  return ingredientsTarget
118
137
 
119
138
  def unpackDataclassCallFunctionRepackDataclass(ingredientsCaller: IngredientsFunction, targetCallableIdentifier: str, shatteredDataclass: ShatteredDataclass) -> IngredientsFunction:
139
+ """
140
+ Transform a caller function to interface with a dataclass-free target function.
141
+
142
+ This function complements `removeDataclassFromFunction` by modifying calling code to work with
143
+ the transformed target function. It implements the unpacking and repacking pattern required
144
+ when a dataclass-based caller needs to invoke a function that has been converted to accept
145
+ individual field parameters instead of dataclass instances.
146
+
147
+ The transformation creates a three-step pattern around the target function call:
148
+ 1. Unpack the dataclass instance into individual field variables.
149
+ 2. Call the target function with the unpacked field values.
150
+ 3. Repack the returned field values back into a dataclass instance.
151
+
152
+ This enables seamless integration between dataclass-based high-level code and optimized
153
+ field-based implementations, maintaining the original interface while enabling performance
154
+ optimizations in the target function.
155
+
156
+ Parameters:
157
+ ingredientsCaller: The calling function definition and its dependencies to be transformed.
158
+ targetCallableIdentifier: The name of the target function being called.
159
+ shatteredDataclass: The decomposed dataclass components providing unpacking and repacking logic.
160
+
161
+ Returns:
162
+ ingredientsCaller: The modified caller function with appropriate unpacking and repacking around the target call.
163
+ """
120
164
  astCallTargetCallable = Make.Call(Make.Name(targetCallableIdentifier), shatteredDataclass.listName4Parameters)
121
165
  replaceAssignTargetCallable = NodeChanger(ClassIsAndAttribute.valueIs(ast.Assign, IfThis.isCallIdentifier(targetCallableIdentifier)), Then.replaceWith(Make.Assign([shatteredDataclass.fragments4AssignmentOrParameters], value=astCallTargetCallable)))
122
166
  unpack4targetCallable = NodeChanger(ClassIsAndAttribute.valueIs(ast.Assign, IfThis.isCallIdentifier(targetCallableIdentifier)), Then.insertThisAbove(shatteredDataclass.listUnpack))