mapFolding 0.12.1__py3-none-any.whl → 0.12.3__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 (37) hide show
  1. mapFolding/__init__.py +46 -20
  2. mapFolding/_theSSOT.py +81 -0
  3. mapFolding/_theTypes.py +148 -0
  4. mapFolding/basecamp.py +62 -47
  5. mapFolding/beDRY.py +100 -73
  6. mapFolding/dataBaskets.py +226 -31
  7. mapFolding/filesystemToolkit.py +161 -107
  8. mapFolding/oeis.py +388 -174
  9. mapFolding/reference/flattened.py +1 -1
  10. mapFolding/someAssemblyRequired/RecipeJob.py +146 -20
  11. mapFolding/someAssemblyRequired/__init__.py +60 -38
  12. mapFolding/someAssemblyRequired/_toolIfThis.py +125 -35
  13. mapFolding/someAssemblyRequired/_toolkitContainers.py +125 -44
  14. mapFolding/someAssemblyRequired/getLLVMforNoReason.py +35 -26
  15. mapFolding/someAssemblyRequired/infoBooth.py +37 -2
  16. mapFolding/someAssemblyRequired/makeAllModules.py +785 -0
  17. mapFolding/someAssemblyRequired/makeJobTheorem2Numba.py +161 -74
  18. mapFolding/someAssemblyRequired/toolkitNumba.py +218 -36
  19. mapFolding/someAssemblyRequired/transformationTools.py +125 -58
  20. mapfolding-0.12.3.dist-info/METADATA +163 -0
  21. mapfolding-0.12.3.dist-info/RECORD +53 -0
  22. {mapfolding-0.12.1.dist-info → mapfolding-0.12.3.dist-info}/WHEEL +1 -1
  23. tests/__init__.py +28 -44
  24. tests/conftest.py +66 -61
  25. tests/test_computations.py +64 -89
  26. tests/test_filesystem.py +25 -1
  27. tests/test_oeis.py +37 -7
  28. tests/test_other.py +29 -2
  29. tests/test_tasks.py +30 -2
  30. mapFolding/datatypes.py +0 -18
  31. mapFolding/someAssemblyRequired/Z0Z_makeAllModules.py +0 -433
  32. mapFolding/theSSOT.py +0 -34
  33. mapfolding-0.12.1.dist-info/METADATA +0 -184
  34. mapfolding-0.12.1.dist-info/RECORD +0 -53
  35. {mapfolding-0.12.1.dist-info → mapfolding-0.12.3.dist-info}/entry_points.txt +0 -0
  36. {mapfolding-0.12.1.dist-info → mapfolding-0.12.3.dist-info}/licenses/LICENSE +0 -0
  37. {mapfolding-0.12.1.dist-info → mapfolding-0.12.3.dist-info}/top_level.txt +0 -0
@@ -380,7 +380,7 @@ def parseDimensions(dimensions: Sequence[int], parameterName: str = 'unnamed par
380
380
  def setCPUlimit(CPUlimit: bool | float | int | None) -> int:
381
381
  # if not (CPUlimit is None or isinstance(CPUlimit, (bool, int, float))):
382
382
  # CPUlimit = oopsieKwargsie(CPUlimit)
383
- # concurrencyLimit = defineConcurrencyLimit(CPUlimit)
383
+ # concurrencyLimit = defineConcurrencyLimit(limit=CPUlimit)
384
384
  # numba.set_num_threads(concurrencyLimit)
385
385
  concurrencyLimitHARDCODED = 1
386
386
  concurrencyLimit = concurrencyLimitHARDCODED
@@ -1,6 +1,38 @@
1
- from astToolkit import parseLogicalPath2astModule, str_nameDOTname
2
- from mapFolding import getPathFilenameFoldsTotal, getPathRootJobDEFAULT, MapFoldingState, packageSettings
3
- from mapFolding import DatatypeElephino as TheDatatypeElephino, DatatypeFoldsTotal as TheDatatypeFoldsTotal, DatatypeLeavesTotal as TheDatatypeLeavesTotal
1
+ """
2
+ Map folding AST transformation system: Configuration management and transformation orchestration.
3
+
4
+ This module provides the configuration orchestration layer of the map folding AST transformation
5
+ system, implementing comprehensive recipes that coordinate the entire transformation process from
6
+ abstract mathematical algorithms to optimized computational modules. The `RecipeJobTheorem2Numba`
7
+ dataclass serves as the central configuration blueprint that bridges pattern recognition, dataclass
8
+ decomposition, function optimization, and Numba compilation into a unified transformation process.
9
+
10
+ The recipe system addresses the complexity of managing transformation parameters across multiple
11
+ stages while maintaining consistency between source algorithm metadata and target optimization
12
+ requirements. The orchestration layer coordinates the systematic extraction of mathematical
13
+ functions from source modules, embedding of concrete parameter values, elimination of dead code
14
+ paths, and generation of standalone Python modules optimized for specific map dimensions through
15
+ the complete transformation process.
16
+
17
+ Configuration management separates source analysis capabilities from target generation parameters,
18
+ enabling systematic exploration of computational spaces through automated generation of optimized
19
+ solvers. Source analysis encompasses parsing and analysis of abstract syntax trees from generic
20
+ algorithm modules, extraction of specific mathematical functions for specialization, and
21
+ identification of dataclass structures for parameter embedding. Target generation coordinates
22
+ creation of standalone Python modules with optimized implementations, integration of Numba
23
+ optimization directives, and preservation of mathematical correctness throughout optimization.
24
+
25
+ The recipe system enables the broader map folding research framework by providing systematic
26
+ control over the transformation process while ensuring that generated modules achieve maximum
27
+ performance through compile-time specialization and runtime optimization strategies.
28
+ """
29
+
30
+ from ast import Module
31
+ from astToolkit import identifierDotAttribute, parseLogicalPath2astModule
32
+ from mapFolding import (
33
+ DatatypeElephino as TheDatatypeElephino, DatatypeFoldsTotal as TheDatatypeFoldsTotal,
34
+ DatatypeLeavesTotal as TheDatatypeLeavesTotal, getPathFilenameFoldsTotal, getPathRootJobDEFAULT, MapFoldingState,
35
+ packageSettings)
4
36
  from mapFolding.someAssemblyRequired import dataclassInstanceIdentifierDEFAULT, ShatteredDataclass
5
37
  from mapFolding.someAssemblyRequired.transformationTools import shatter_dataclassesDOTdataclass
6
38
  from pathlib import Path, PurePosixPath
@@ -9,54 +41,121 @@ import dataclasses
9
41
 
10
42
  @dataclasses.dataclass
11
43
  class RecipeJobTheorem2Numba:
44
+ """Configuration recipe for generating Numba-optimized map folding computation jobs.
45
+
46
+ This dataclass serves as the central configuration hub for the code transformation
47
+ pipeline that converts generic map folding algorithms into highly optimized,
48
+ specialized computation modules. The recipe encapsulates all parameters required
49
+ for source code analysis, target file generation, datatype mapping, and compilation
50
+ optimization settings.
51
+
52
+ The transformation process operates by extracting functions from source modules,
53
+ embedding concrete parameter values, eliminating dead code paths, and generating
54
+ standalone Python modules optimized for specific map dimensions. These generated
55
+ modules achieve maximum performance through Numba just-in-time compilation and
56
+ embedded compile-time constants.
57
+
58
+ The recipe maintains both source configuration (where to find the generic algorithm)
59
+ and target configuration (where to write the optimized module), along with the
60
+ computational state that provides concrete values for the transformation process.
61
+
62
+ Attributes
63
+ ----------
64
+ state: The map folding computation state containing dimensions and initial values.
65
+ foldsTotalEstimated: Estimated total number of folds for progress tracking (0).
66
+ shatteredDataclass: Deconstructed dataclass metadata for code transformation.
67
+ source_astModule: Parsed AST of the source module containing the generic algorithm.
68
+ sourceCountCallable: Name of the counting function to extract ('count').
69
+ sourceLogicalPathModuleDataclass: Logical path to the dataclass module.
70
+ sourceDataclassIdentifier: Name of the source dataclass ('MapFoldingState').
71
+ sourceDataclassInstance: Instance identifier for the dataclass.
72
+ sourcePathPackage: Path to the source package.
73
+ sourcePackageIdentifier: Name of the source package.
74
+ pathPackage: Override path for the target package (None).
75
+ pathModule: Override path for the target module directory.
76
+ fileExtension: File extension for generated modules.
77
+ pathFilenameFoldsTotal: Path for writing fold count results.
78
+ packageIdentifier: Target package identifier (None).
79
+ logicalPathRoot: Logical path root corresponding to filesystem directory.
80
+ moduleIdentifier: Target module identifier.
81
+ countCallable: Name of the counting function in generated module.
82
+ dataclassIdentifier: Target dataclass identifier.
83
+ dataclassInstance: Target dataclass instance identifier.
84
+ logicalPathModuleDataclass: Logical path to target dataclass module.
85
+ DatatypeFoldsTotal: Type alias for fold count datatype.
86
+ DatatypeElephino: Type alias for intermediate computation datatype.
87
+ DatatypeLeavesTotal: Type alias for leaf count datatype.
88
+ """
89
+
12
90
  state: MapFoldingState
13
91
  # TODO create function to calculate `foldsTotalEstimated`
14
92
  foldsTotalEstimated: int = 0
15
93
  shatteredDataclass: ShatteredDataclass = dataclasses.field(default=None, init=True) # pyright: ignore[reportAssignmentType]
16
94
 
17
- # ========================================
18
- # Source
19
- source_astModule = parseLogicalPath2astModule('mapFolding.syntheticModules.theorem2Numba')
95
+ # Source -----------------------------------------
96
+ source_astModule: Module = parseLogicalPath2astModule('mapFolding.syntheticModules.theorem2Numba') # noqa: RUF009
20
97
  sourceCountCallable: str = 'count'
21
98
 
22
- sourceLogicalPathModuleDataclass: str_nameDOTname = 'mapFolding.dataBaskets'
99
+ sourceLogicalPathModuleDataclass: identifierDotAttribute = 'mapFolding.dataBaskets'
23
100
  sourceDataclassIdentifier: str = 'MapFoldingState'
24
101
  sourceDataclassInstance: str = dataclassInstanceIdentifierDEFAULT
25
102
 
26
- sourcePathPackage: PurePosixPath | None = PurePosixPath(packageSettings.pathPackage)
27
- sourcePackageIdentifier: str | None = packageSettings.packageName
103
+ sourcePathPackage: PurePosixPath | None = PurePosixPath(packageSettings.pathPackage) # noqa: RUF009
104
+ sourcePackageIdentifier: str | None = packageSettings.identifierPackage
28
105
 
29
- # ========================================
30
- # Filesystem (names of physical objects)
106
+ # Filesystem, names of physical objects ------------------------------------------
31
107
  pathPackage: PurePosixPath | None = None
32
- pathModule: PurePosixPath | None = PurePosixPath(getPathRootJobDEFAULT())
108
+ pathModule: PurePosixPath | None = PurePosixPath(getPathRootJobDEFAULT()) # noqa: RUF009
33
109
  """ `pathModule` will override `pathPackage` and `logicalPathRoot`."""
34
110
  fileExtension: str = packageSettings.fileExtension
35
111
  pathFilenameFoldsTotal: PurePosixPath = dataclasses.field(default=None, init=True) # pyright: ignore[reportAssignmentType]
36
112
 
37
- # ========================================
38
- # Logical identifiers (as opposed to physical identifiers)
113
+ # Logical identifiers, as opposed to physical identifiers ------------------------
39
114
  packageIdentifier: str | None = None
40
- logicalPathRoot: str_nameDOTname | None = None
115
+ logicalPathRoot: identifierDotAttribute | None = None
41
116
  """ `logicalPathRoot` likely corresponds to a physical filesystem directory."""
42
117
  moduleIdentifier: str = dataclasses.field(default=None, init=True) # pyright: ignore[reportAssignmentType]
43
118
  countCallable: str = sourceCountCallable
44
119
  dataclassIdentifier: str | None = sourceDataclassIdentifier
45
120
  dataclassInstance: str | None = sourceDataclassInstance
46
- logicalPathModuleDataclass: str_nameDOTname | None = sourceLogicalPathModuleDataclass
121
+ logicalPathModuleDataclass: identifierDotAttribute | None = sourceLogicalPathModuleDataclass
47
122
 
48
- # ========================================
49
- # Datatypes
123
+ # Datatypes ------------------------------------------
50
124
  DatatypeFoldsTotal: TypeAlias = TheDatatypeFoldsTotal
51
125
  DatatypeElephino: TypeAlias = TheDatatypeElephino
52
126
  DatatypeLeavesTotal: TypeAlias = TheDatatypeLeavesTotal
53
127
 
54
128
  def _makePathFilename(self,
55
129
  pathRoot: PurePosixPath | None = None,
56
- logicalPathINFIX: str_nameDOTname | None = None,
130
+ logicalPathINFIX: identifierDotAttribute | None = None,
57
131
  filenameStem: str | None = None,
58
132
  fileExtension: str | None = None,
59
133
  ) -> PurePosixPath:
134
+ """Construct a complete file path from component parts.
135
+
136
+ (AI generated docstring)
137
+
138
+ This helper method builds filesystem paths by combining a root directory,
139
+ optional subdirectory structure, filename stem, and file extension. It provides
140
+ sensible defaults for missing components based on the recipe configuration.
141
+
142
+ Parameters
143
+ ----------
144
+ pathRoot : PurePosixPath | None = None
145
+ Base directory path. Defaults to package path or current directory.
146
+ logicalPathINFIX : identifierDotAttribute | None = None
147
+ Dot-separated path segments to insert between root and filename.
148
+ filenameStem : str | None = None
149
+ Base filename without extension. Defaults to module identifier.
150
+ fileExtension : str | None = None
151
+ File extension including dot. Defaults to configured extension.
152
+
153
+ Returns
154
+ -------
155
+ pathFilename : PurePosixPath
156
+ Complete file path as a `PurePosixPath` object.
157
+
158
+ """
60
159
  if pathRoot is None:
61
160
  pathRoot = self.pathPackage or PurePosixPath(Path.cwd())
62
161
  if logicalPathINFIX:
@@ -71,12 +170,39 @@ class RecipeJobTheorem2Numba:
71
170
 
72
171
  @property
73
172
  def pathFilenameModule(self) -> PurePosixPath:
173
+ """Generate the complete path and filename for the output module.
174
+
175
+ (AI generated docstring)
176
+
177
+ This property computes the target location where the generated computation
178
+ module will be written. It respects the `pathModule` override if specified,
179
+ otherwise constructs the path using the default package structure.
180
+
181
+ Returns
182
+ -------
183
+ pathFilename : PurePosixPath
184
+ Complete path to the target module file.
185
+
186
+ """
74
187
  if self.pathModule is None:
75
188
  return self._makePathFilename()
76
189
  else:
77
190
  return self._makePathFilename(pathRoot=self.pathModule, logicalPathINFIX=None)
78
191
 
79
- def __post_init__(self):
192
+ def __post_init__(self) -> None:
193
+ """Initialize computed fields and validate configuration after dataclass creation.
194
+
195
+ (AI generated docstring)
196
+
197
+ This method performs post-initialization setup including deriving module
198
+ identifier from map shape if not explicitly provided, setting default paths
199
+ for fold total output files, and creating shattered dataclass metadata for
200
+ code transformations.
201
+
202
+ The initialization ensures all computed fields are properly set based on
203
+ the provided configuration and sensible defaults.
204
+
205
+ """
80
206
  pathFilenameFoldsTotal = PurePosixPath(getPathFilenameFoldsTotal(self.state.mapShape))
81
207
 
82
208
  if self.moduleIdentifier is None: # pyright: ignore[reportUnnecessaryComparison]
@@ -1,52 +1,79 @@
1
1
  """
2
- Code Transformation Framework for Algorithm Optimization and Testing
2
+ Map folding AST transformation system: Comprehensive framework for converting dataclass-based algorithms to optimized implementations.
3
3
 
4
- This package implements a comprehensive framework for programmatically analyzing, transforming, and generating optimized
5
- Python code. It serves as the algorithmic optimization engine for the mapFolding package, enabling the conversion of
6
- readable, functional implementations into highly-optimized variants with verified correctness.
4
+ This subpackage implements a sophisticated Abstract Syntax Tree (AST) transformation system specifically designed to convert
5
+ high-level dataclass-based map folding algorithms into highly optimized, Numba-compatible implementations. The transformation
6
+ system addresses a fundamental challenge in high-performance scientific computing: bridging the gap between maintainable,
7
+ object-oriented algorithm implementations and the performance requirements of computationally intensive mathematical research.
7
8
 
8
- ## Core Architecture Components
9
+ The map folding problem domain involves complex combinatorial calculations that can require hours or days to complete for specific
10
+ dimensional configurations. While dataclass-based implementations provide clean, maintainable interfaces for managing complex
11
+ mathematical state, these objects cannot be directly processed by Numba's just-in-time compiler, which excels at optimizing
12
+ operations on primitive values and tuples. This subpackage resolves this architectural tension through systematic AST manipulation
13
+ that preserves algorithmic correctness while enabling dramatic performance improvements.
9
14
 
10
- 1. **AST Manipulation Tools**
11
- - Pattern recognition with composable predicates (ifThis)
12
- - Node access with consistent interfaces (DOT)
13
- - AST traversal and transformation (NodeChanger, NodeTourist)
14
- - AST construction with sane defaults (Make)
15
- - Node transformation operations (grab, Then)
15
+ ## System Architecture
16
16
 
17
- 2. **Container and Organization**
18
- - Import tracking and management (LedgerOfImports)
19
- - Function packaging with dependencies (IngredientsFunction)
20
- - Module assembly with structured components (IngredientsModule)
21
- - Recipe configuration for generating optimized code (RecipeSynthesizeFlow)
22
- - Dataclass decomposition for compatibility (ShatteredDataclass)
17
+ The transformation system operates through a carefully orchestrated sequence of specialized modules, each contributing essential
18
+ capabilities to the complete transformation process:
23
19
 
24
- 3. **Optimization assembly lines**
25
- - General-purpose Numba acceleration (makeNumbaFlow)
26
- - Job-specific optimization for concrete parameters (makeJobNumba)
27
- - Specialized component transformation (decorateCallableWithNumba)
20
+ ### Foundation Layer: Pattern Recognition and Structural Analysis
21
+ - `_toolIfThis`: Extended predicate functions for identifying specific code patterns in AST nodes, particularly conditional
22
+ expressions and control flow structures essential to map folding computations
23
+ - `_toolkitContainers`: Dataclass decomposition containers that extract individual fields, type annotations, and reconstruction
24
+ logic from dataclass definitions into manipulatable AST components
28
25
 
29
- ## Integration with Testing Framework
26
+ ### Operational Core: Transformation Implementation
27
+ - `transformationTools`: Core functions executing dataclass decomposition, function signature transformation, and calling
28
+ convention adaptation that convert dataclass-accepting functions into primitive-parameter equivalents
29
+ - `toolkitNumba`: Numba integration tools providing just-in-time compilation optimization with configurable performance parameters
30
+ and strategic compiler directive application
30
31
 
31
- The transformation components are extensively tested through the package's test suite, which provides specialized
32
- fixtures and utilities for validating both the transformation process and the resulting optimized code:
32
+ ### Configuration and Orchestration
33
+ - `infoBooth`: Configuration constants, computational complexity estimates, and default identifiers for systematic module generation and optimization decision-making
34
+ - `RecipeJob`: Configuration management dataclasses that coordinate transformation parameters across multiple stages while
35
+ maintaining consistency between source algorithms and target optimizations
36
+ - `makeAllModules`: Comprehensive transformation orchestration tools that execute complete transformation processes for diverse
37
+ computational strategies and performance characteristics
38
+ - `makeJobTheorem2Numba`: Specialized job generation implementing the complete transformation sequence to produce standalone, highly optimized computation modules
33
39
 
34
- - **syntheticDispatcherFixture**: Creates and tests a complete Numba-optimized module using RecipeSynthesizeFlow
35
- configuration
40
+ ### Utility Extensions
41
+ - `getLLVMforNoReason`: Standalone utility for extracting LLVM Intermediate Representation from compiled modules for debugging and optimization analysis
36
42
 
37
- - **test_writeJobNumba**: Tests the job-specific optimization process with RecipeJob
43
+ ## Transformation Process
38
44
 
39
- These fixtures enable users to test their own custom recipes and job configurations with minimal effort. See the
40
- documentation in tests/__init__.py for details on extending the test suite for custom implementations.
45
+ The complete transformation follows a systematic three-stage pattern:
41
46
 
42
- The framework balances multiple optimization levels - from general algorithmic improvements to parameter-specific
43
- optimizations - while maintaining the ability to verify correctness at each transformation stage through the integrated
44
- test suite.
47
+ 1. **Analysis and Decomposition**: Pattern recognition identifies dataclass structures and dependencies, followed by decomposition
48
+ into constituent AST components including field definitions, type annotations, and initialization patterns.
49
+
50
+ 2. **Function Optimization**: Core transformations convert functions accepting dataclass parameters into functions accepting
51
+ individual primitive parameters, with systematic updates to signatures, return types, and calling conventions.
52
+
53
+ 3. **Compilation Integration**: Numba decorators with carefully configured optimization parameters are applied to transformed
54
+ functions, enabling aggressive just-in-time compilation with performance characteristics suitable for large-scale computational
55
+ research.
56
+
57
+ ## Generated Module Characteristics
58
+
59
+ The transformation system produces standalone Python modules with embedded constants replacing parameterized values, eliminated
60
+ dead code paths, optimized data structures, Numba compilation directives, progress feedback for long-running calculations, and
61
+ consistent naming conventions with systematic filesystem organization. These modules maintain mathematical correctness while
62
+ providing significant performance improvements essential to map folding research computational demands.
63
+
64
+ ## Usage Guidance
65
+
66
+ Begin exploration with `infoBooth` for understanding configuration options and complexity estimates. Proceed to
67
+ `transformationTools` for core transformation capabilities, then examine `RecipeJob` for orchestration patterns. Advanced users
68
+ developing custom transformations should study `_toolIfThis` and `_toolkitContainers` for foundational pattern recognition and
69
+ structural manipulation capabilities.
70
+
71
+ The transformation system represents the culmination of systematic AST manipulation research, enabling previously intractable
72
+ calculations through the strategic application of compiler optimization techniques to abstract mathematical algorithms.
45
73
  """
46
74
 
47
75
  from mapFolding.someAssemblyRequired.infoBooth import (
48
76
  dataclassInstanceIdentifierDEFAULT as dataclassInstanceIdentifierDEFAULT,
49
- raiseIfNoneGitHubIssueNumber3 as raiseIfNoneGitHubIssueNumber3,
50
77
  sourceCallableDispatcherDEFAULT as sourceCallableDispatcherDEFAULT,
51
78
  )
52
79
 
@@ -56,8 +83,3 @@ from mapFolding.someAssemblyRequired._toolkitContainers import (
56
83
  DeReConstructField2ast as DeReConstructField2ast,
57
84
  ShatteredDataclass as ShatteredDataclass,
58
85
  )
59
-
60
- def raiseIfNone[TypeSansNone](returnTarget: TypeSansNone | None) -> TypeSansNone:
61
- if returnTarget is None:
62
- raise ValueError('Return is None.')
63
- return returnTarget
@@ -1,58 +1,148 @@
1
1
  """
2
- AST Node Predicate and Access Utilities for Pattern Matching and Traversal
2
+ Map folding AST transformation system: Foundation pattern matching and filtering predicates.
3
3
 
4
- This module provides utilities for accessing and matching AST nodes in a consistent way. It contains three primary
5
- classes:
4
+ This module establishes the foundational layer of the map folding AST transformation system by
5
+ providing specialized predicate functions for identifying specific code patterns in Abstract
6
+ Syntax Trees. The transformation system converts high-level dataclass-based map folding algorithms
7
+ into optimized computational modules through systematic AST manipulation, beginning with precise
8
+ pattern recognition capabilities defined here.
6
9
 
7
- 1. DOT: Provides consistent accessor methods for AST node attributes across different node types, simplifying the access
8
- to node properties.
10
+ The predicates extend `astToolkit.IfThis` with domain-specific functions that recognize conditional
11
+ expressions and control flow structures essential to map folding computations. These patterns include
12
+ attribute comparisons against specific values, loop termination conditions based on counting variables,
13
+ and bounds checking operations that characterize map folding algorithm structures.
9
14
 
10
- 2. be: Offers type-guard functions that verify AST node types, enabling safe type narrowing for static type checking and
11
- improving code safety.
15
+ Pattern recognition serves as the entry point for the broader transformation system that decomposes
16
+ dataclass-dependent algorithms, applies performance optimizations, and generates specialized modules
17
+ optimized for Numba just-in-time compilation. The precise identification of these structural patterns
18
+ enables subsequent transformation stages to apply targeted optimizations while preserving mathematical
19
+ correctness.
12
20
 
13
- 3. ifThis: Contains predicate functions for matching AST nodes based on various criteria, enabling precise targeting of
14
- nodes for analysis or transformation.
15
-
16
- These utilities form the foundation of the pattern-matching component in the AST manipulation framework, working in
17
- conjunction with the NodeChanger and NodeTourist classes to enable precise and targeted code transformations. Together,
18
- they implement a declarative approach to AST manipulation that separates node identification (ifThis), type verification
19
- (be), and data access (DOT).
21
+ Classes:
22
+ IfThis: Extended predicate class with specialized methods for matching attribute comparisons
23
+ and control flow patterns involving namespaced identifiers essential to map folding
24
+ algorithm transformations.
20
25
  """
21
26
 
22
- from astToolkit import Be, DOT, IfThis as astToolkit_IfThis
27
+ from astToolkit import Be, IfThis as astToolkit_IfThis
23
28
  from collections.abc import Callable
24
- from typing import TypeGuard
29
+ from typing_extensions import TypeIs
25
30
  import ast
26
31
 
27
32
  class IfThis(astToolkit_IfThis):
28
- """
29
- Provide predicate functions for matching and filtering AST nodes based on various criteria.
33
+ """Provide predicate functions for matching and filtering AST nodes based on various criteria.
30
34
 
31
- The ifThis class contains static methods that generate predicate functions used to test whether AST nodes match
32
- specific criteria. These predicates can be used with NodeChanger and NodeTourist to identify and process specific
35
+ (AI generated docstring)
36
+
37
+ The `IfThis` `class` contains static methods that generate predicate functions used to test whether AST nodes match
38
+ specific criteria. These predicates can be used with `NodeChanger` and `NodeTourist` to identify and process specific
33
39
  patterns in the AST.
34
40
 
35
- The class provides predicates for matching various node types, attributes, identifiers, and structural patterns,
41
+ The `class` provides predicates for matching various node types, attributes, identifiers, and structural patterns,
36
42
  enabling precise targeting of AST elements for analysis or transformation.
43
+
37
44
  """
45
+
46
+ @staticmethod
47
+ def isAttributeNamespaceIdentifierLessThanOrEqual0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeIs[ast.Compare]]:
48
+ """Generate a predicate that matches comparison expressions testing if a namespaced attribute is less than or equal to 0.
49
+
50
+ (AI generated docstring)
51
+
52
+ This function creates a predicate that identifies AST nodes representing comparisons
53
+ of the form `namespace.identifier <= 0`. It's used to identify conditional
54
+ expressions that test non-positive values of counting variables or similar constructs.
55
+
56
+ Parameters
57
+ ----------
58
+ namespace : str
59
+ The namespace or object name containing the attribute.
60
+ identifier : str
61
+ The attribute name to test.
62
+
63
+ Returns
64
+ -------
65
+ predicate : Callable[[ast.AST], TypeIs[ast.Compare]]
66
+ A predicate function that returns `True` for `Compare` nodes matching the pattern.
67
+
68
+ """
69
+ return lambda node: (Be.Compare.leftIs(IfThis.isAttributeNamespaceIdentifier(namespace, identifier))(node)
70
+ and Be.Compare.opsIs(lambda at: Be.LtE(at[0]))(node)
71
+ )
72
+
38
73
  @staticmethod
39
- def isAttributeNamespaceIdentifierGreaterThan0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeGuard[ast.Compare] | bool]:
40
- return lambda node: (Be.Compare(node)
41
- and IfThis.isAttributeNamespaceIdentifier(namespace, identifier)(DOT.left(node))
74
+ def isAttributeNamespaceIdentifierGreaterThan0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeIs[ast.Compare] | bool]:
75
+ """Generate a predicate that matches comparison expressions testing if a namespaced attribute is greater than 0.
76
+
77
+ (AI generated docstring)
78
+
79
+ This function creates a predicate that identifies AST nodes representing comparisons
80
+ of the form `namespace.identifier > 0`. It's commonly used to identify conditional
81
+ expressions that test positive values of counting variables or similar constructs.
82
+
83
+ Parameters
84
+ ----------
85
+ namespace : str
86
+ The namespace or object name containing the attribute.
87
+ identifier : str
88
+ The attribute name to test.
89
+
90
+ Returns
91
+ -------
92
+ predicate : Callable[[ast.AST], TypeIs[ast.Compare]]
93
+ A predicate function that returns `True` for `Compare` nodes matching the pattern.
94
+
95
+ """
96
+ return lambda node: (Be.Compare.leftIs(IfThis.isAttributeNamespaceIdentifier(namespace, identifier))(node)
42
97
  and Be.Gt(node.ops[0])
43
98
  and IfThis.isConstant_value(0)(node.comparators[0]))
44
- @staticmethod
45
- def isIfAttributeNamespaceIdentifierGreaterThan0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeGuard[ast.If] | bool]:
46
- return lambda node: (Be.If(node)
47
- and IfThis.isAttributeNamespaceIdentifierGreaterThan0(namespace, identifier)(DOT.test(node)))
48
99
 
49
100
  @staticmethod
50
- def isWhileAttributeNamespaceIdentifierGreaterThan0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeGuard[ast.While] | bool]:
51
- return lambda node: (Be.While(node)
52
- and IfThis.isAttributeNamespaceIdentifierGreaterThan0(namespace, identifier)(DOT.test(node)))
101
+ def isIfAttributeNamespaceIdentifierGreaterThan0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeIs[ast.If]]:
102
+ """Generate a predicate that matches If statements testing if a namespaced attribute is greater than 0.
103
+
104
+ (AI generated docstring)
105
+
106
+ This function creates a predicate that identifies AST nodes representing conditional
107
+ statements of the form `if namespace.identifier > 0:`. It's used to find control
108
+ flow structures that depend on positive values of specific attributes.
109
+
110
+ Parameters
111
+ ----------
112
+ namespace : str
113
+ The namespace or object name containing the attribute.
114
+ identifier : str
115
+ The attribute name to test.
116
+
117
+ Returns
118
+ -------
119
+ predicate : Callable[[ast.AST], TypeIs[ast.If]]
120
+ A predicate function that returns `True` for `If` nodes with the specified test condition.
121
+
122
+ """
123
+ return Be.If.testIs(IfThis.isAttributeNamespaceIdentifierGreaterThan0(namespace, identifier))
53
124
 
54
125
  @staticmethod
55
- def isAttributeNamespaceIdentifierLessThanOrEqual0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeGuard[ast.Compare] | bool]:
56
- return lambda node: (Be.Compare(node)
57
- and IfThis.isAttributeNamespaceIdentifier(namespace, identifier)(DOT.left(node))
58
- and Be.LtE(node.ops[0]))
126
+ def isWhileAttributeNamespaceIdentifierGreaterThan0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeIs[ast.While]]:
127
+ """Generate a predicate that matches While loops testing if a namespaced attribute is greater than 0.
128
+
129
+ (AI generated docstring)
130
+
131
+ This function creates a predicate that identifies AST nodes representing loop
132
+ statements of the form `while namespace.identifier > 0:`. It's used to find
133
+ iteration constructs that continue while specific attributes remain positive.
134
+
135
+ Parameters
136
+ ----------
137
+ namespace : str
138
+ The namespace or object name containing the attribute.
139
+ identifier : str
140
+ The attribute name to test.
141
+
142
+ Returns
143
+ -------
144
+ predicate : Callable[[ast.AST], TypeIs[ast.While]]
145
+ A predicate function that returns `True` for `While` nodes with the specified test condition.
146
+
147
+ """
148
+ return Be.While.testIs(IfThis.isAttributeNamespaceIdentifierGreaterThan0(namespace, identifier))