Alnoms Core API Reference (OSS)
This reference is the single source of truth for the Alnoms industrial standard open-core package. All documentation below is generated deterministically from the sovereign source code.
βοΈ Core Engine (alnoms.core)
The orchestration and performance profiling logic for Pre-Deployment Governance.
β±οΈ Performance Profiling
Industrialβgrade performance analyzer for algorithm benchmarking.
The Profiler supports:
- Precision timing using
timeit.default_timer - Warmup runs to stabilize CPU cache and branch predictors
- Statistical aggregation (min, mean, median)
- Doublingβtest complexity estimation
- Decoratorβbased profiling for normal program flow
- Stressβsuite benchmarking for headβtoβhead comparisons
Attributes:
| Name | Type | Description |
|---|---|---|
repeats |
int
|
Number of timed runs per benchmark. |
warmup |
int
|
Number of untimed warmup runs. |
mode |
str
|
Statistical mode for final timing ('min', 'mean', 'median'). |
Source code in src/alnoms/core/profiler.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | |
__init__(repeats=5, warmup=1, mode='min')
Initialize the Profiler with benchmark settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repeats
|
int
|
Number of timed runs per benchmark. |
5
|
warmup
|
int
|
Number of warmup runs to prime CPU cache. |
1
|
mode
|
str
|
Statistical mode ('min', 'mean', 'median'). |
'min'
|
Notes
repeatsis clamped to at least 1.warmupis clamped to at least 0.
Source code in src/alnoms/core/profiler.py
benchmark(func, *args)
Benchmark a function with GC disabled for timing purity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
Function to benchmark. |
required |
*args
|
Any
|
Arguments passed to the function. |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Execution time in seconds, aggregated using the configured mode. |
Notes
- Deepcopies arguments to avoid mutation across runs.
- Disables garbage collection to reduce jitter.
Source code in src/alnoms/core/profiler.py
print_analysis(func_name, results)
Print a formatted table from a doubling test.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func_name
|
str
|
Name of the analyzed function. |
required |
results
|
List[Dict[str, Any]]
|
Output from |
required |
Source code in src/alnoms/core/profiler.py
print_decorator_report()
Print a summary table of all decoratorβtracked timings.
Displays
- Function/block label
- Number of calls
- Average time
- Total time
Source code in src/alnoms/core/profiler.py
profile(func)
Decorator for lightweight profiling during normal execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
Function to wrap. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
Wrapped function that records execution time. |
Notes
- Stores timing data under
self._profile_stats[func.__name__].
Source code in src/alnoms/core/profiler.py
run_doubling_test(func, input_gen, start_n=50, rounds=3, timeout=15.0)
Perform doubling analysis to estimate algorithmic complexity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
Algorithm under test. |
required |
input_gen
|
Callable
|
Function generating input for size N. |
required |
start_n
|
int
|
Initial input size. |
50
|
rounds
|
int
|
Number of doubling iterations. |
3
|
timeout
|
float
|
Maximum allowed runtime for the entire test. |
15.0
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: A list of records containing: - "N": Input size - "Time": Execution time - "Ratio": T(2N) / T(N) - "Complexity": Estimated BigβO class |
Notes
- Automatically increases recursion limit for deep algorithms.
- Stops early if timeout is exceeded.
Source code in src/alnoms/core/profiler.py
run_stress_suite(funcs, input_gen, n_values=[1000, 2000, 4000])
Run multiple algorithms across multiple input sizes.
Useful for headβtoβhead comparisons in research, teaching, and performance governance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
funcs
|
Dict[str, Callable]
|
Mapping of function names to callables. |
required |
input_gen
|
Callable
|
Data generator for size N. |
required |
n_values
|
List[int]
|
Input sizes to test. |
[1000, 2000, 4000]
|
Returns:
| Type | Description |
|---|---|
Dict[int, Dict[str, float]]
|
Dict[int, Dict[str, float]]:
Nested mapping of |
Source code in src/alnoms/core/profiler.py
stopwatch(label='Block')
Context manager for precision timing of a code block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Identifier for the timed block. |
'Block'
|
Yields:
| Name | Type | Description |
|---|---|---|
None |
None
|
Execution of the wrapped block. |
Side Effects
- Records elapsed time under
self._profile_stats[label].
Source code in src/alnoms/core/profiler.py
π§ Analysis & Decision Engine
Central orchestrator for the Alnoms governance pipeline.
This class coordinates:
- Script execution and dynamic profiling
- Static AST pattern detection
- Loopβdepth and static complexity estimation
- Optional empirical scaling tests
- Metadataβdriven algorithmic recommendations
- Fixerβbased prescriptive remediation
All methods are static and the class is stateless.
Source code in src/alnoms/core/analyzer.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | |
analyze_file(path, deep=False, target_override=None, gen_name=None, data_file=None, start_n=50, rounds=3)
staticmethod
Perform full governance analysis on a Python script.
Pipeline
- Execute + profile the script
- Run static AST pattern detection
- Compute loop depth and static complexity
- Optionally run empirical scaling tests
- Integrate DecisionEngine metadata
- Integrate Fixers for prescriptive remediation
- Produce a unified governance report
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the Python script. |
required |
deep
|
bool
|
Whether to run empirical scaling tests. |
False
|
target_override
|
str
|
Explicit function name for empirical tests. |
None
|
gen_name
|
str
|
Name of a standard generator. |
None
|
data_file
|
str
|
Path to a data file. |
None
|
start_n
|
int
|
Initial input size for empirical tests. |
50
|
rounds
|
int
|
Number of doubling rounds. |
3
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
A complete governance analysis report. |
Source code in src/alnoms/core/analyzer.py
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | |
profile_script(path)
staticmethod
Profile a script and extract the top slowest developer functions.
Uses cProfile to gather cumulative execution time and filters out
nonβuser code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the Python script. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
A tuple containing: - list: Top 5 slowest functions with timing info. - float: Total cumulative execution time. - module: The executed module object. |
Source code in src/alnoms/core/analyzer.py
run_empirical_test(module, slowest_func_name, gen_name=None, data_file=None, start_n=50, rounds=3, func_ast=None)
staticmethod
Run empirical doubling tests on a target function.
Input data can come from:
- A script-defined
data_gen() - A standard generator in
alnoms.core.generators - A data file loaded via
DataReader
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Any
|
The executed script module. |
required |
slowest_func_name
|
str
|
Function selected for empirical testing. |
required |
gen_name
|
str
|
Name of a standard generator. |
None
|
data_file
|
str
|
Path to a data file. |
None
|
start_n
|
int
|
Initial input size. |
50
|
rounds
|
int
|
Number of doubling rounds. |
3
|
Returns:
| Type | Description |
|---|---|
Optional[List[Dict[str, Any]]]
|
Optional[List[Dict[str, Any]]]: Empirical results or None. |
Source code in src/alnoms/core/analyzer.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | |
run_script(path)
staticmethod
Execute a Python script in an isolated module namespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the Python script. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
module |
The executed module object. |
Source code in src/alnoms/core/analyzer.py
Deterministic ruleβbased mapping for OSSβtier algorithm selection.
The DecisionEngine provides a stable, nonβadaptive mapping from detected performance patterns to recommended dataβstructure or algorithmic remedies. All identifiers returned by this engine use snake_case to satisfy OSSβtier test and governance requirements.
Metadata lookup is also performed using snake_case keys, matching the canonical identifiers stored in the MetadataRegistry.
Source code in src/alnoms/core/decision_engine.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
__init__(metadata)
Initialize the decision engine with metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
Dict[str, dict]
|
Mapping of snake_case algorithm identifiers to metadata dictionaries. Each metadata entry typically includes complexity, category, tier, and module import path. |
required |
Source code in src/alnoms/core/decision_engine.py
decide(pattern, intent=None)
Primary OSS entrypoint for algorithm selection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
Detected performance pattern. |
required |
intent
|
Optional[str]
|
Developer intent for nested loops. |
None
|
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: Snake_case recommended algorithm identifier. |
Source code in src/alnoms/core/decision_engine.py
decide_algorithm(pattern, intent=None)
Return the recommended algorithm identifier (snake_case).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
Detected performance pattern identifier. |
required |
intent
|
Optional[str]
|
Developer intent extracted from AST heuristics. Relevant only
for nestedβloop patterns. Examples include:
|
None
|
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: Snake_case algorithm identifier, or None if no mapping exists. |
Source code in src/alnoms/core/decision_engine.py
decide_fix(pattern, intent=None)
Return a humanβreadable fix recommendation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
Detected performance pattern. |
required |
intent
|
Optional[str]
|
Developer intent for nested loops. |
None
|
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Optional[str]: Short prescriptive recommendation string, or None. |
Source code in src/alnoms/core/decision_engine.py
decide_metadata(algorithm)
Retrieve metadata for a recommended algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
algorithm
|
str
|
Snake_case algorithm identifier returned by |
required |
Returns:
| Type | Description |
|---|---|
Optional[dict]
|
Optional[dict]: Metadata dictionary for the algorithm, or None if not found. |
Source code in src/alnoms/core/decision_engine.py
π² Data Generators & I/O
Collection of deterministic and highβperformance dataset generators.
These generators are used throughout the Alnoms ecosystem for:
- Algorithm benchmarking
- Worstβcase and bestβcase scenario construction
- Empirical scaling tests (doubling tests)
- Teaching and demonstration notebooks
- Reproducible research workflows
All methods are static and sideβeffectβfree.
Source code in src/alnoms/core/generators.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | |
large_scale_dataset(n)
staticmethod
Generate a large dataset optimized for highβvolume research.
Attempts to use NumPy for highβthroughput integer generation. If NumPy
is unavailable, falls back to the pureβPython random_array generator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of integers to generate. |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A list of random integers suitable for largeβscale tests. |
Source code in src/alnoms/core/generators.py
random_array(n, lo=0, hi=1000)
staticmethod
Generate an array of random integers.
This is the default dependencyβfree generator used across the OSS tier.
It relies solely on Python's builtβin random module and is suitable
for lightweight benchmarking or environments where NumPy is unavailable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of integers to generate. |
required |
lo
|
int
|
Lower bound of the random range (inclusive). |
0
|
hi
|
int
|
Upper bound of the random range (inclusive). |
1000
|
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A list of |
Source code in src/alnoms/core/generators.py
reverse_sorted_array(n)
staticmethod
Generate a descending array from nβ1 to 0.
This is a convenience wrapper around sorted_array(reverse=True) and
is frequently used to construct worstβcase inputs for algorithms such
as insertion sort or bubble sort.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of elements to generate. |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A descending list of integers. |
Source code in src/alnoms/core/generators.py
sorted_array(n, reverse=False)
staticmethod
Generate a sorted array of integers from 0 to nβ1.
Useful for constructing bestβcase or worstβcase inputs for sorting algorithms and search routines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of elements to generate. |
required |
reverse
|
bool
|
If True, return the array in descending order. |
False
|
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A sorted list of integers. |
Source code in src/alnoms/core/generators.py
square_matrices(n)
staticmethod
Generate a pair of NΓN matrices filled with constant values.
Designed for benchmarking matrix multiplication algorithms where the computational complexityβnot the numerical valuesβis the primary focus.
Complexity
- Time: O(NΒ²) to initialize both matrices.
- Space: O(NΒ²) for storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Dimension of each square matrix. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple
|
A tuple |
Source code in src/alnoms/core/generators.py
Utility functions for loading test datasets from files.
All methods are static and designed for predictable, dependencyβfree behavior. They support common formats used in algorithm benchmarking, including whitespaceβseparated integers, tokens, and raw lines.
Source code in src/alnoms/core/io.py
read_all_ints(path)
staticmethod
Read all whitespaceβseparated integers from a file.
The file may contain integers separated by spaces, tabs, or newlines. This format is commonly used for sorting and searching benchmarks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Absolute or relative path to the input file. |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
List[int]: A list of parsed integers. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
ValueError
|
If any token cannot be parsed as an integer. |
Source code in src/alnoms/core/io.py
read_all_strings(path)
staticmethod
Read all whitespaceβseparated tokens from a file.
Useful for loading datasets for Trie benchmarks, MSD/LSD string sorts, and tokenβbased algorithm tests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Absolute or relative path to the input file. |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of string tokens. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
Source code in src/alnoms/core/io.py
read_lines(path)
staticmethod
Read all lines from a file, stripping leading and trailing whitespace.
Empty lines are preserved as empty strings. This is useful for lineβoriented algorithms, text processing, and structured input formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Absolute or relative path to the input file. |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of cleaned lines. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
Source code in src/alnoms/core/io.py
𧬠Algorithms (alnoms.dsa.algorithms)
The algorithm pillar provides precision implementations for complex computational problems.
πΈοΈ Graph Theory
BreadthβFirst Search Paths.
Provides a breadthβfirst search (BFS)βbased shortestβpath finder for undirected graphs. BFS computes the shortest path in terms of number of edges from a designated source vertex to all reachable vertices.
Design Characteristics: - Computes unweighted shortest paths - Produces predecessor links and distance levels - Time Complexity: O(V + E) - Space Complexity: O(V)
BreadthFirstPaths
Computes BFSβbased shortest paths from a single source vertex.
This class performs a breadthβfirst search from a specified source vertex and records both predecessor links and distance levels. BFS guarantees shortest paths in unweighted graphs.
Attributes:
| Name | Type | Description |
|---|---|---|
_s |
int
|
The source vertex. |
_marked |
List[bool]
|
Marks whether each vertex has been visited. |
_edge_to |
List[int]
|
Predecessor links for path reconstruction. |
_dist_to |
List[float]
|
Number of edges in the shortest path. |
Source code in src/alnoms/dsa/algorithms/graph/breadth_first_paths.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
__init__(G, s)
Initializes BFS search from a source vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Graph
|
The graph to search. |
required |
s
|
int
|
The source vertex. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the source vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/breadth_first_paths.py
dist_to(v)
Returns the BFS shortestβpath distance to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex whose distance is requested. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Number of edges in the shortest path. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/breadth_first_paths.py
has_path_to(v)
Checks whether a path exists from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if reachable, otherwise False. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/breadth_first_paths.py
path_to(v)
Returns the shortest path from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The destination vertex. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Iterable[int]]
|
Optional[Iterable[int]]: A sequence of vertices forming the |
Optional[Iterable[int]]
|
shortest path, or None if no path exists. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/breadth_first_paths.py
DepthβFirst Search Orderings.
Computes preorder, postorder, and reverseβpostorder vertex orderings for a directed graph using depthβfirst search (DFS). These orderings are fundamental in algorithms such as topological sorting and strongly connected components.
Design Characteristics: - DFSβbased vertex ordering - Reverse postorder supports topological sorting in DAGs - Time Complexity: O(V + E) - Space Complexity: O(V)
DepthFirstOrder
Computes DFSβbased vertex orderings for a directed graph.
This class performs a full DFS over all vertices of a directed graph and records the reverse postorder sequence. Reverse postorder is particularly useful for topological sorting in directed acyclic graphs (DAGs).
Attributes:
| Name | Type | Description |
|---|---|---|
_marked |
List[bool]
|
Marks whether each vertex has been visited. |
_reverse_post |
Deque[int]
|
Vertices in reverse postorder. |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_order.py
__init__(G)
Initializes DFS order computation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Digraph
|
The directed graph whose orderings are computed. |
required |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_order.py
reverse_post()
Returns vertices in reverse postorder.
Returns:
| Type | Description |
|---|---|
Iterable[int]
|
Iterable[int]: A sequence of vertices in reverse postorder. |
DepthβFirst Search Paths.
Provides a depthβfirst search (DFS)βbased path finder for undirected graphs. Starting from a designated source vertex, the algorithm explores all reachable vertices and records predecessor links that allow path reconstruction.
Design Characteristics: - Computes reachability from a single source - Produces DFS tree predecessor links - Paths are not guaranteed to be shortest - Time Complexity: O(V + E) - Space Complexity: O(V)
DepthFirstPaths
Computes DFSβbased paths from a single source vertex.
This class performs a depthβfirst search from a specified source vertex and records the predecessor of each visited vertex. These predecessor links allow reconstruction of any path from the source to a reachable vertex.
Attributes:
| Name | Type | Description |
|---|---|---|
_s |
int
|
The source vertex. |
_marked |
List[bool]
|
Marks whether each vertex has been visited. |
_edge_to |
List[int]
|
Predecessor links for path reconstruction. |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_paths.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
__init__(G, s)
Initializes DFS search from a source vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Graph
|
The graph to search. |
required |
s
|
int
|
The source vertex. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the source vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_paths.py
has_path_to(v)
Checks whether a path exists from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if reachable, otherwise False. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_paths.py
path_to(v)
Returns a path from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The destination vertex. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Iterable[int]]
|
Optional[Iterable[int]]: A sequence of vertices forming a path |
Optional[Iterable[int]]
|
from the source to |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_paths.py
Dijkstra's Shortest Paths.
Implements the singleβsource shortestβpath algorithm for edgeβweighted directed graphs with nonβnegative edge weights. The algorithm computes the shortest path tree rooted at a specified source vertex using a binary heapβbased priority queue.
Design Characteristics: - Supports arbitrary directed graphs with nonβnegative weights - Produces shortestβpath distances and predecessor edges - Uses lazy deletion in the priority queue - Time Complexity: O(E log V) - Space Complexity: O(V)
DijkstraSP
Computes shortest paths in a weighted directed graph.
This class computes the shortest path from a single source vertex to all other vertices in an edgeβweighted digraph with nonβnegative edge weights. Distances and predecessor edges are stored for subsequent queries.
Attributes:
| Name | Type | Description |
|---|---|---|
_dist_to |
List[float]
|
Shortest known distance to each vertex. |
_edge_to |
List[Optional[DirectedEdge]]
|
Last edge on the shortest known path to each vertex. |
_pq |
List[tuple]
|
Minβheap storing (distance, vertex) pairs. |
Source code in src/alnoms/dsa/algorithms/graph/dijkstra_sp.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
__init__(G, s)
Initializes the shortestβpath computation from a source vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
EdgeWeightedDigraph
|
The input directed graph. |
required |
s
|
int
|
The source vertex. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any edge in the graph has a negative weight. |
Source code in src/alnoms/dsa/algorithms/graph/dijkstra_sp.py
dist_to(v)
Returns the shortestβpath distance to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex whose distance is requested. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The shortest distance, or infinity if unreachable. |
Source code in src/alnoms/dsa/algorithms/graph/dijkstra_sp.py
has_path_to(v)
Checks whether a path exists from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if a path exists, otherwise False. |
Source code in src/alnoms/dsa/algorithms/graph/dijkstra_sp.py
path_to(v)
Returns the shortest path from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The destination vertex. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Iterable[DirectedEdge]]
|
Optional[Iterable[DirectedEdge]]: A sequence of edges forming |
Optional[Iterable[DirectedEdge]]
|
the shortest path, or None if no path exists. |
Source code in src/alnoms/dsa/algorithms/graph/dijkstra_sp.py
Topological Sorting.
Provides a topological ordering of a directed acyclic graph (DAG) using depthβfirst search finishing times. The implementation relies on the reverse postorder of a DFS traversal. If the graph contains a cycle, the resulting order is not a valid topological sort, but the algorithm still produces an ordering based on DFS structure.
Design Characteristics: - O(V + E) time - Uses DFS reverseβpostorder - Assumes the input graph is a DAG unless validated externally
Classes:
| Name | Description |
|---|---|
Topological |
Computes a topological order of a directed graph. |
Topological
Computes a topological order of a directed graph.
The ordering is derived from the reverse postorder of a depthβfirst search. This yields a valid topological order if and only if the graph is acyclic. Cycle detection is not performed here; callers should validate DAG properties externally if correctness is required.
Source code in src/alnoms/dsa/algorithms/graph/topological.py
__init__(G)
Initializes the topological sort computation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Digraph
|
Directed graph on which to compute the ordering. |
required |
Source code in src/alnoms/dsa/algorithms/graph/topological.py
has_order()
Indicates whether a topological order is available.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if an order was computed. This does not guarantee |
bool
|
that the graph is acyclic; it only reflects that an ordering |
|
bool
|
exists based on DFS finishing times. |
Source code in src/alnoms/dsa/algorithms/graph/topological.py
order()
Returns the computed topological order.
Returns:
| Type | Description |
|---|---|
Iterable[int]
|
Iterable[int]: Vertices in topological order. |
π’ Sorting & Searching
Bubble Sort.
Implements the classic bubble sort algorithm, which repeatedly scans the array and swaps adjacent elements that are out of order. This version includes the standard earlyβtermination optimization: if a full pass completes with no swaps, the array is already sorted. An optional visualization mode yields intermediate array states after each swap.
Design Characteristics: - Inβplace sorting - Stable behavior - O(NΒ²) average and worstβcase time - O(N) bestβcase time on already sorted input - O(1) auxiliary space - Visualization mode yields swapβstep snapshots
Classes:
| Name | Description |
|---|---|
BubbleSort |
Static implementation of bubble sort. |
BubbleSort
Bubble sort implementation.
Repeatedly compares adjacent elements and swaps them if they are in the wrong order. The algorithm terminates early if a full pass completes without any swaps, making it efficient for nearly sorted input.
Source code in src/alnoms/dsa/algorithms/sorting/bubble_sort.py
bubble_sort(arr, visualize=False)
staticmethod
Sorts the input list using bubble sort.
If visualize is True, the function returns a generator that
yields the array state after each swap. Otherwise, it returns the
fully sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
List[Any]
|
The list to sort. |
required |
visualize
|
bool
|
Whether to yield intermediate states. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[Any], Generator[List[Any], None, None]]
|
Union[List[Any], Generator[List[Any], None, None]]: Sorted list or generator of intermediate states. |
Complexity
Source code in src/alnoms/dsa/algorithms/sorting/bubble_sort.py
Insertion Sort.
Implements the classic insertion sort algorithm, which builds the sorted array incrementally by inserting each element into its correct position relative to the alreadyβsorted prefix. The algorithm performs extremely well on partially sorted arrays and small subarrays. An optional visualization mode yields intermediate array states after each swap.
Design Characteristics: - Inβplace sorting - Stable behavior - O(N) bestβcase time on nearly sorted input - O(NΒ²) worstβcase time - O(1) auxiliary space - Visualization mode yields swapβstep snapshots
Classes:
| Name | Description |
|---|---|
InsertionSort |
Static implementation of insertion sort. |
InsertionSort
Insertion sort implementation.
Builds the sorted array one element at a time by shifting larger elements to the right and inserting the current element into its correct position. Particularly effective for small or partially sorted datasets.
Source code in src/alnoms/dsa/algorithms/sorting/insertion_sort.py
insertion_sort(arr, visualize=False)
staticmethod
Sorts the input list using insertion sort.
If visualize is True, the function returns a generator that
yields the array state after each swap. Otherwise, it returns the
fully sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
List[Any]
|
The list to sort. |
required |
visualize
|
bool
|
Whether to yield intermediate states. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[Any], Generator[List[Any], None, None]]
|
Union[List[Any], Generator[List[Any], None, None]]: Sorted list or generator of intermediate states. |
Complexity
Source code in src/alnoms/dsa/algorithms/sorting/insertion_sort.py
Merge Sort.
Implements the classic divideβandβconquer merge sort algorithm using an auxiliary array for merging. The algorithm guarantees O(N log N) time regardless of input distribution and is stable by construction. An optional visualization mode yields intermediate array states after each merge operation.
Design Characteristics: - Stable sorting - Deterministic O(N log N) time - Requires O(N) auxiliary space - Visualization mode yields mergeβstep snapshots
Classes:
| Name | Description |
|---|---|
MergeSort |
Static implementation of topβdown merge sort. |
MergeSort
Topβdown recursive merge sort implementation.
The algorithm recursively divides the array into halves, sorts each half, and merges them using an auxiliary array. This version supports visualization by yielding intermediate states after each merge step.
Source code in src/alnoms/dsa/algorithms/sorting/merge_sort.py
merge_sort(arr, visualize=False)
staticmethod
Sorts the input list using merge sort.
If visualize is True, the function returns a generator that
yields the array state after each merge operation. Otherwise, it
returns the fully sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
List[Any]
|
The list to sort. |
required |
visualize
|
bool
|
Whether to yield intermediate states. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[Any], Generator[List[Any], None, None]]
|
Union[List[Any], Generator[List[Any], None, None]]: Sorted list or generator of intermediate states. |
Complexity
Source code in src/alnoms/dsa/algorithms/sorting/merge_sort.py
Quick Sort (3βWay Partitioning).
Implements Dijkstraβs 3βway partitioning variant of Quicksort, which handles duplicate keys efficiently by dividing the array into three regions: less than, equal to, and greater than the pivot. This approach improves performance on inputs with many repeated values.
Design Characteristics: - Inβplace sorting - Averageβcase O(N log N) time - Worstβcase O(NΒ²) time (rare with randomized input) - O(log N) recursion depth - Optional visualization mode yielding intermediate array states
Classes:
| Name | Description |
|---|---|
QuickSort |
Static implementation of 3βway partitioning Quicksort. |
QuickSort
3βway partitioning Quicksort implementation.
Uses Dijkstraβs partitioning strategy to efficiently handle arrays with many duplicate keys. The algorithm recursively sorts the subarrays containing elements less than and greater than the pivot.
Source code in src/alnoms/dsa/algorithms/sorting/quick_sort.py
quick_sort(arr, visualize=False)
staticmethod
Sorts the input list using 3βway partitioning Quicksort.
If visualize is True, the function returns a generator that
yields the array state after each swap or partitioning step.
Otherwise, it returns the fully sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
List[Any]
|
The list to sort. |
required |
visualize
|
bool
|
Whether to yield intermediate states. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[Any], Generator[List[Any], None, None]]
|
Union[List[Any], Generator[List[Any], None, None]]: Sorted list or generator of intermediate states. |
Complexity
Source code in src/alnoms/dsa/algorithms/sorting/quick_sort.py
Selection Sort.
Provides a simple comparisonβbased sorting algorithm that repeatedly selects the minimum element and swaps it into its correct position. This implementation supports optional stepβbyβstep visualization via a generator interface.
Design Characteristics: - Inβplace sorting - Deterministic O(NΒ²) time - O(1) auxiliary space - Visualization mode yields intermediate array states
Classes:
| Name | Description |
|---|---|
SelectionSort |
Static implementation of the selection sort algorithm. |
SelectionSort
Selection sort implementation.
Repeatedly scans the unsorted portion of the array to find the minimum element and swaps it into its correct position. The algorithm is simple, stable in behavior, and useful for educational and demonstrative purposes.
Source code in src/alnoms/dsa/algorithms/sorting/selection_sort.py
selection_sort(arr, visualize=False)
staticmethod
Sorts the input list using selection sort.
If visualize is True, the function returns a generator that
yields the array state after each swap. Otherwise, it returns the
fully sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
List[Any]
|
The list to sort. |
required |
visualize
|
bool
|
Whether to yield intermediate states. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[Any], Generator[List[Any], None, None]]
|
Union[List[Any], Generator[List[Any], None, None]]: Sorted list or generator of intermediate states. |
Complexity
Source code in src/alnoms/dsa/algorithms/sorting/selection_sort.py
Binary Search Utilities.
Provides classic binary search operations on sorted arrays, including exactβmatch search and rank computation. Both operations run in O(log N) time and assume that the input list is already sorted in ascending order.
Design Characteristics: - Deterministic O(log N) time - Works on any comparable key type - Rank operation supports arrays with duplicates - No side effects; functions operate on the input list as readβonly
Classes:
| Name | Description |
|---|---|
BinarySearch |
Static utilities for binary search and rank. |
BinarySearch
Binary search and rank utilities.
Implements exactβmatch binary search and a leftβleaning rank operation that counts how many elements are strictly less than a given key. Both methods assume the input list is sorted.
Source code in src/alnoms/dsa/algorithms/searching/binary_search.py
rank(a, key)
staticmethod
Returns the number of elements strictly less than key.
Uses a leftβleaning binary search to find the first index at
which key could be inserted while maintaining sorted order.
This yields the count of elements smaller than key and works
efficiently even with many duplicates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
List[Any]
|
Sorted list to examine. |
required |
key
|
Any
|
Target key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Count of elements strictly less than |
Complexity
Source code in src/alnoms/dsa/algorithms/searching/binary_search.py
search(a, key)
staticmethod
Performs binary search for key in a sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
List[Any]
|
Sorted list to search. |
required |
key
|
Any
|
Target key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Index of |
Complexity
Source code in src/alnoms/dsa/algorithms/searching/binary_search.py
π― Pointers
PointerβBased Algorithms.
Provides classic twoβpointer techniques, including Floydβs TortoiseβandβHare cycle detection algorithm for singly linked lists. These algorithms rely on constantβspace pointer manipulation and are widely used in linkedβlist processing and fast/slow traversal patterns.
Design Characteristics:
- O(1) auxiliary space
- O(N) cycle detection
- Works on any singly linked list with next references
Classes:
| Name | Description |
|---|---|
CycleDetector |
Implements Floydβs cycleβfinding algorithm. |
CycleDetector
Cycle detection using Floydβs TortoiseβandβHare algorithm.
Uses two pointers moving at different speeds to determine whether a singly linked list contains a cycle. If the fast pointer ever meets the slow pointer, a cycle exists.
Source code in src/alnoms/dsa/algorithms/pointers/cycle_detector.py
has_cycle(head)
staticmethod
Detects whether a singly linked list contains a cycle.
The algorithm advances a slow pointer by one step and a fast pointer by two steps. If the list contains a cycle, the two pointers eventually meet. If the fast pointer reaches the end of the list, no cycle exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
head
|
Optional[Node]
|
Head of the singly linked list. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if a cycle exists, otherwise False. |
Complexity
Source code in src/alnoms/dsa/algorithms/pointers/cycle_detector.py
π¦ Data Structures (alnoms.dsa.structures)
Low-latency, memory-efficient structures designed for high-scale environments.
π Linear Structures
Bag (Unordered Collection).
Defines a lightweight collection type that supports insertion but does not support removal. A Bag is useful for collecting items and iterating over them without imposing any ordering guarantees. Internally, the Bag is backed by a singly linked list, enabling O(1) insertion.
Design Characteristics: - Unordered collection - O(1) insertion at the front - O(N) iteration - No removal operations
Classes:
| Name | Description |
|---|---|
Bag |
A simple unordered collection supporting fast insertion. |
Bag
Bases: Generic[T]
An unordered collection supporting fast insertion.
Items are stored in a singly linked list. The Bag does not support removal; its purpose is to collect items and allow iteration over them. The iteration order is LIFO due to front insertion, but the order is not semantically meaningful.
Source code in src/alnoms/dsa/structures/bag.py
__init__()
Initializes an empty Bag.
Attributes:
| Name | Type | Description |
|---|---|---|
_first |
Optional[Node]
|
Reference to the first node. |
_n |
int
|
Number of items stored. |
__iter__()
Iterates over the items in the Bag.
Yields:
| Name | Type | Description |
|---|---|---|
T |
T
|
Items stored in the Bag. Order is LIFO but not meaningful. |
Source code in src/alnoms/dsa/structures/bag.py
add(item)
Adds an item to the Bag.
This operation runs in O(1) time by inserting the new item at the front of the linked list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to add. |
required |
Source code in src/alnoms/dsa/structures/bag.py
is_empty()
Checks whether the Bag is empty.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the Bag contains no items. |
size()
Returns the number of items in the Bag.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total number of stored items. |
Alnoms Data Structure: FIFO Queue (LinkedβList Backed).
Provides a generic, typeβsafe FIFO (FirstβIn FirstβOut) queue implementation using a singly linked list with explicit head and tail references. This design guarantees O(1) enqueue and dequeue operations without requiring array resizing or circularβbuffer bookkeeping.
The queue supports:
- O(1) enqueue at the tail
- O(1) dequeue from the head
- Safe iteration from front to back
- Deterministic memory behavior with no hidden reallocations
This module is part of the Alnoms OSS dataβstructures suite and is optimized for teaching, benchmarking, and algorithmic experimentation. All operations are implemented with predictable worstβcase complexity.
Queue
Bases: Generic[T]
A FIFO (FirstβIn FirstβOut) queue implemented using a linked list.
This implementation maintains references to both the head (_first)
and tail (_last) nodes, ensuring O(1) enqueue and dequeue
operations. The queue grows dynamically without requiring array
resizing, making it suitable for workloads requiring predictable
constantβtime behavior.
Source code in src/alnoms/dsa/structures/queue.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
__init__()
Initializes an empty queue.
Attributes:
| Name | Type | Description |
|---|---|---|
_first |
Optional[Node]
|
Reference to the front of the queue. |
_last |
Optional[Node]
|
Reference to the end of the queue. |
_n |
int
|
Number of items currently stored. |
Source code in src/alnoms/dsa/structures/queue.py
__iter__()
Iterates over the queue from front to back.
Yields:
| Name | Type | Description |
|---|---|---|
T |
T
|
Items in FIFO order, starting from the front. |
Source code in src/alnoms/dsa/structures/queue.py
dequeue()
Removes and returns the item at the front of the queue.
This operation runs in O(1) time by removing the head node.
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The item previously at the front of the queue. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the queue is empty. |
Source code in src/alnoms/dsa/structures/queue.py
enqueue(item)
Adds an item to the end of the queue.
This operation runs in O(1) time by inserting a new node at the tail of the linked list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to add to the queue. |
required |
Source code in src/alnoms/dsa/structures/queue.py
is_empty()
Checks whether the queue is empty.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the queue contains no items, otherwise False. |
peek()
Returns the item at the front of the queue without removing it.
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The item currently at the front. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the queue is empty. |
Source code in src/alnoms/dsa/structures/queue.py
size()
Returns the number of items in the queue.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of elements stored. |
Linked-List-Based Stack.
Implements a generic LIFO (Last-In First-Out) stack using a linked list backing. This design guarantees O(1) worst-case push and pop operations by avoiding array resizing and capacity management.
Features
- O(1) push and pop
- Dynamic, node-based storage
- Type-parameterized (generic) API
- Safe iteration from top to bottom
Stack
Bases: Generic[T]
A LIFO (LastβIn FirstβOut) stack implemented using a linked list.
This implementation guarantees O(1) worstβcase time for both push
and pop operations by avoiding the resizing overhead associated
with arrayβbased stacks. The stack grows dynamically through linked
nodes, making it suitable for workloads requiring predictable
constantβtime operations.
Source code in src/alnoms/dsa/structures/stack.py
__init__()
Initializes an empty stack.
Attributes:
| Name | Type | Description |
|---|---|---|
_first |
Optional[Node]
|
Reference to the top node. |
_n |
int
|
Number of items currently stored. |
__iter__()
Iterates over the stack from top to bottom.
Yields:
| Name | Type | Description |
|---|---|---|
T |
T
|
Items in LIFO order, starting from the top. |
Source code in src/alnoms/dsa/structures/stack.py
is_empty()
Checks whether the stack is empty.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the stack contains no items, otherwise False. |
peek()
Returns the item at the top of the stack without removing it.
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The item currently at the top. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the stack is empty. |
Source code in src/alnoms/dsa/structures/stack.py
pop()
Removes and returns the most recently added item.
This operation runs in O(1) time by removing the head node.
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The item previously at the top of the stack. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the stack is empty. |
Source code in src/alnoms/dsa/structures/stack.py
push(item)
Pushes an item onto the top of the stack.
This operation runs in O(1) time by inserting a new node at the head of the linked list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to push onto the stack. |
required |
Source code in src/alnoms/dsa/structures/stack.py
size()
Returns the number of items in the stack.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of elements stored. |
Singly Linked List (Foundational Data Structure).
Provides a minimal, textbookβgrade implementation of a singly linked list supporting O(1) insertions at the head and linearβtime traversal. This structure is useful for workloads requiring predictable insertion performance without the resizing overhead of arrayβbacked lists.
Features
β’ O(1) insertion at the head β’ Linearβtime traversal and search β’ Nodeβbased dynamic memory allocation β’ Pythonic iteration support
This module is part of the Alnoms Data Structures suite and is designed for clarity, determinism, and mkdocstringsβcompatible documentation.
SinglyLinkedList
A foundational singly linked list implementation.
This structure supports O(1) insertions at the head and linear-time traversal from head to tail. It is suitable for workloads requiring predictable insertion performance without the resizing overhead of array-backed lists.
Source code in src/alnoms/dsa/structures/singly_linked_list.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
__init__()
Initializes an empty singly linked list.
Attributes:
| Name | Type | Description |
|---|---|---|
head |
Optional[Node]
|
Reference to the first node in the list. |
_size |
int
|
Number of nodes currently stored. |
Source code in src/alnoms/dsa/structures/singly_linked_list.py
__iter__()
Iterates through the list from head to tail.
Yields:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The data stored in each node. |
Source code in src/alnoms/dsa/structures/singly_linked_list.py
__len__()
Returns the number of nodes in the list.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The total number of elements. |
append(data)
Appends a new node to the end of the list.
This operation runs in O(N) time due to the need to traverse to the tail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The value to append. |
required |
Source code in src/alnoms/dsa/structures/singly_linked_list.py
display()
Returns a string representation of the list.
Useful for debugging and visualization.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A formatted representation such as |
Source code in src/alnoms/dsa/structures/singly_linked_list.py
insert_at_head(data)
Inserts a new node at the beginning of the list.
This operation runs in O(1) time by updating the head pointer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The value to insert. |
required |
Source code in src/alnoms/dsa/structures/singly_linked_list.py
is_empty()
Checks whether the list contains any elements.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the list is empty, otherwise False. |
remove(data)
Removes the first occurrence of a value from the list.
This operation runs in O(N) time due to linear search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The value to remove. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if a node was removed, otherwise False. |
Source code in src/alnoms/dsa/structures/singly_linked_list.py
Doubly Linked List.
Provides a bidirectional linked list supporting O(1) insertion at both the head and tail. Each node maintains references to its predecessor and successor, enabling efficient traversal and structural updates.
Design Characteristics: - Bidirectional traversal - O(1) prepend and append - O(N) search and removal - Deterministic memory behavior
Classes:
| Name | Description |
|---|---|
DoublyLinkedList |
A doubly linked list supporting head/tail operations. |
DoublyLinkedList
Bases: Generic[T]
A doubly linked list supporting bidirectional traversal.
The list maintains references to both the head and tail nodes, enabling O(1) insertion at either end. Removal of arbitrary values runs in O(N) time due to linear search.
Source code in src/alnoms/dsa/structures/doubly_linked_list.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
__init__()
Initializes an empty doubly linked list.
Attributes:
| Name | Type | Description |
|---|---|---|
head |
Optional[DoublyNode]
|
First node in the list. |
tail |
Optional[DoublyNode]
|
Last node in the list. |
_size |
int
|
Number of nodes in the list. |
Source code in src/alnoms/dsa/structures/doubly_linked_list.py
__iter__()
Iterates through the list from head to tail.
Yields:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The data stored in each node. |
Source code in src/alnoms/dsa/structures/doubly_linked_list.py
__len__()
Returns the number of nodes in the list.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The size of the list. |
append(data)
Appends a node to the end of the list.
This operation runs in O(1) time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The value to append. |
required |
Source code in src/alnoms/dsa/structures/doubly_linked_list.py
display_forward()
Returns a string representation from head to tail.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A formatted representation of the list. |
Source code in src/alnoms/dsa/structures/doubly_linked_list.py
is_empty()
Checks whether the list is empty.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the list contains no elements. |
prepend(data)
Inserts a node at the beginning of the list.
This operation runs in O(1) time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The value to prepend. |
required |
Source code in src/alnoms/dsa/structures/doubly_linked_list.py
remove(data)
Removes the first occurrence of a specific value.
This operation runs in O(N) time due to linear search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The value to remove. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if a node was removed, otherwise False. |
Source code in src/alnoms/dsa/structures/doubly_linked_list.py
π³ Trees & Graphs
Binary Search Tree (BST).
Provides a recursive implementation of an ordered symbol table using a binary search tree. Keys must be comparable, and the structure supports ordered operations such as min, max, floor, rank, and sorted iteration. Deletion uses Hibbard's algorithm.
Design Characteristics: - Ordered keyβvalue storage - Inβorder traversal yields sorted keys - Hibbard deletion for node removal - Rank and selection operations supported - Worstβcase height O(N) if unbalanced
Classes:
| Name | Description |
|---|---|
BinarySearchTree |
Ordered symbol table implemented using a BST. |
BinarySearchTree
Binary Search Tree (BST) symbol table.
Keys are maintained in sorted order. Supports search, insertion, deletion (Hibbard), and ordered operations such as min, max, and floor. All operations are implemented recursively.
Source code in src/alnoms/dsa/structures/binary_search_tree.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
__init__()
contains(key)
Checks whether the BST contains key.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if present, otherwise False. |
delete(key)
Deletes key from the BST using Hibbard deletion.
delete_min()
floor(key)
Returns the largest key β€ key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
Target key. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
Optional[Any]: Floor key, or None if no such key exists. |
Source code in src/alnoms/dsa/structures/binary_search_tree.py
get(key)
Returns the value associated with key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
Key to search for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
Optional[Any]: Value if found, otherwise None. |
Source code in src/alnoms/dsa/structures/binary_search_tree.py
is_empty()
Checks whether the BST is empty.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if empty, otherwise False. |
keys()
Returns all keys in sorted order.
Returns:
| Type | Description |
|---|---|
List[Any]
|
List[Any]: Sorted list of keys. |
max()
Returns the largest key.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the BST is empty. |
min()
Returns the smallest key.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the BST is empty. |
put(key, val)
Inserts or updates a keyβvalue pair.
If val is None, the key is deleted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
Key to insert. |
required |
val
|
Any
|
Value to associate. |
required |
Source code in src/alnoms/dsa/structures/binary_search_tree.py
size()
Returns the number of keyβvalue pairs in the table.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total number of stored entries. |
Graph Data Structures.
Provides a lightweight, adjacencyβlistβbased undirected graph optimized
for algorithmic experimentation, teaching, and benchmarking. The graph
supports efficient edge insertion and adjacency iteration while
maintaining predictable memory usage proportional to V + E.
Design Characteristics: - Representation: Adjacency lists (space complexity O(V + E)). - Performance: - Add edge: O(1) - Iterate adjacency: O(degree(v)) - Check membership: O(degree(v)) - Selfβloops and parallel edges are permitted by default.
Classes:
| Name | Description |
|---|---|
Graph |
Undirected graph implemented using adjacency lists. |
Graph
Undirected graph implemented using adjacency lists.
Each vertex maintains a list of its adjacent vertices. The structure is optimized for sparse graphs and supports efficient adjacency iteration and constantβtime edge insertion.
Source code in src/alnoms/dsa/structures/graphs.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
E()
V()
__init__(V)
Initializes an empty graph with V vertices and zero edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
V
|
int
|
Number of vertices in the graph. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/alnoms/dsa/structures/graphs.py
__repr__()
Returns a string representation of the graph.
The format lists each vertex followed by its adjacency list.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Humanβreadable representation of the graph. |
Source code in src/alnoms/dsa/structures/graphs.py
add_edge(v, w)
Adds an undirected edge between vertices v and w.
Both vertices must be valid indices in the range 0 to
V - 1. Parallel edges and selfβloops are allowed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
First vertex. |
required |
w
|
int
|
Second vertex. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If either vertex index is out of bounds. |
Source code in src/alnoms/dsa/structures/graphs.py
adj(v)
Returns the vertices adjacent to v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex whose neighbors are requested. |
required |
Returns:
| Type | Description |
|---|---|
Iterable[int]
|
Iterable[int]: A list of adjacent vertices. |
Source code in src/alnoms/dsa/structures/graphs.py
degree(v)
Returns the degree of vertex v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex whose degree is requested. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of adjacent vertices. |
Source code in src/alnoms/dsa/structures/graphs.py
Directed Graph (Digraph).
Defines a lightweight adjacencyβlistβbased directed graph. Each vertex maintains a list of outgoing edges, and indegree counts are tracked explicitly. The structure supports efficient adjacency iteration, constantβtime edge insertion, and construction of the graph's reverse.
Design Characteristics: - Representation: Adjacency lists of integers. - Performance: - Add edge: O(1) - Iterate outgoing edges: O(outdegree(v)) - Compute reverse graph: O(V + E) - Selfβloops and parallel edges are permitted.
Classes:
| Name | Description |
|---|---|
Digraph |
Directed graph with adjacency lists and indegree tracking. |
Digraph
Directed graph implemented using adjacency lists.
Each vertex maintains a list of outgoing edges. Indegree counts are stored explicitly to support algorithms that rely on incoming edge information. The structure is suitable for topological sorting, SCC algorithms, and general directed graph processing.
Source code in src/alnoms/dsa/structures/digraph.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
E()
V()
Returns the number of vertices in the digraph.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total vertex count. |
__init__(V)
Initializes an empty digraph with V vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
V
|
int
|
Number of vertices. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/alnoms/dsa/structures/digraph.py
add_edge(v, w)
Adds a directed edge from v to w.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
Source vertex. |
required |
w
|
int
|
Destination vertex. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If either vertex index is out of bounds. |
Source code in src/alnoms/dsa/structures/digraph.py
adj(v)
Returns all vertices reachable from v via outgoing edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The source vertex. |
required |
Returns:
| Type | Description |
|---|---|
Iterable[int]
|
Iterable[int]: Outgoing neighbors of |
Source code in src/alnoms/dsa/structures/digraph.py
in_degree(v)
Returns the number of edges entering vertex v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Indegree of |
out_degree(v)
Returns the number of edges leaving vertex v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Outdegree of |
reverse()
Returns a new digraph with all edges reversed.
Useful for algorithms such as strongly connected components (SCC) where reverse graph traversal is required.
Returns:
| Name | Type | Description |
|---|---|---|
Digraph |
Digraph
|
A new digraph with reversed edge directions. |
Source code in src/alnoms/dsa/structures/digraph.py
EdgeβWeighted Graph.
Provides an undirected graph where each edge carries an associated weight. This structure is used in classical graph algorithms such as Minimum Spanning Trees (MST) and Shortest Paths. The graph is stored using adjacency lists, with each vertex maintaining a list of incident weighted edges.
Design Characteristics:
- Representation: Adjacency lists of Edge objects.
- Performance:
- Add edge: O(1)
- Iterate adjacency: O(degree(v))
- Parallel edges and selfβloops are permitted.
Classes:
| Name | Description |
|---|---|
EdgeWeightedGraph |
Undirected weighted graph backed by adjacency lists. |
EdgeWeightedGraph
Undirected weighted graph implemented using adjacency lists.
Each vertex maintains a list of incident Edge objects. The graph
supports efficient adjacency iteration and constantβtime edge
insertion. This structure is suitable for MST and shortestβpath
algorithms that operate on weighted graphs.
Source code in src/alnoms/dsa/structures/edge_weighted_graph.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
E()
V()
Returns the number of vertices in the graph.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total vertex count. |
__init__(V)
Initializes an empty weighted graph with V vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
V
|
int
|
Number of vertices. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/alnoms/dsa/structures/edge_weighted_graph.py
add_edge(e)
Adds a weighted undirected edge to the graph.
The edge is inserted into the adjacency lists of both endpoints. Parallel edges and selfβloops are allowed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
e
|
Edge
|
The edge to add. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If either endpoint is out of bounds. |
Source code in src/alnoms/dsa/structures/edge_weighted_graph.py
adj(v)
Returns all weighted edges incident to vertex v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex whose incident edges are requested. |
required |
Returns:
| Type | Description |
|---|---|
Iterable[Edge]
|
Iterable[Edge]: List of edges adjacent to |
Source code in src/alnoms/dsa/structures/edge_weighted_graph.py
edges()
Returns all edges in the graph without duplicates.
For each undirected edge, only the instance where the opposite endpoint is greater than the current vertex is included.
Returns:
| Type | Description |
|---|---|
Iterable[Edge]
|
Iterable[Edge]: All unique edges in the graph. |
Source code in src/alnoms/dsa/structures/edge_weighted_graph.py
EdgeβWeighted Directed Graph.
Provides a directed graph where each edge carries an associated weight.
The structure is implemented using adjacency lists, with each vertex
maintaining a list of outgoing DirectedEdge objects. This design
supports efficient adjacency iteration and constantβtime edge insertion.
Design Characteristics:
- Representation: Adjacency lists of DirectedEdge objects.
- Performance:
- Add edge: O(1)
- Iterate outgoing edges: O(outdegree(v))
- Parallel edges and selfβloops are permitted.
Classes:
| Name | Description |
|---|---|
EdgeWeightedDigraph |
Directed weighted graph backed by adjacency lists. |
EdgeWeightedDigraph
Directed weighted graph implemented using adjacency lists.
Each vertex maintains a list of outgoing DirectedEdge objects.
The structure is suitable for shortestβpath algorithms such as
Dijkstra, BellmanβFord, and DAG relaxations.
Source code in src/alnoms/dsa/structures/edge_weighted_digraph.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
E()
Returns the number of edges in the digraph.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total edge count. |
V()
Returns the number of vertices in the digraph.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total vertex count. |
__init__(V)
Initializes an empty edgeβweighted digraph with V vertices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
V
|
int
|
Number of vertices. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/alnoms/dsa/structures/edge_weighted_digraph.py
add_edge(e)
Adds a directed weighted edge to the digraph.
The edge is inserted into the adjacency list of its source vertex. Parallel edges and selfβloops are allowed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
e
|
DirectedEdge
|
The edge to add. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If either endpoint is out of bounds. |
Source code in src/alnoms/dsa/structures/edge_weighted_digraph.py
adj(v)
Returns all outgoing edges from vertex v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The source vertex. |
required |
Returns:
| Type | Description |
|---|---|
Iterable[DirectedEdge]
|
Iterable[DirectedEdge]: Outgoing edges from |
Source code in src/alnoms/dsa/structures/edge_weighted_digraph.py
edges()
Returns all edges in the digraph.
Returns:
| Type | Description |
|---|---|
Iterable[DirectedEdge]
|
Iterable[DirectedEdge]: All directed edges. |
Source code in src/alnoms/dsa/structures/edge_weighted_digraph.py
π Hash Tables
Hash Table Implementations.
Provides classic symbol table implementations based on hashing, including separate chaining and (optionally) linear probing variants. Designed as textbook-grade, inspectable data structures for algorithmic education and performance governance experiments.
Features
- Hash-based key-value storage
- Separate chaining collision handling
- Hashable keys, arbitrary values
- Deterministic, reference-friendly implementation
SeparateChainingHashST
Hash table implementation using separate chaining.
This symbol table stores keyβvalue pairs in an array of buckets,
where each bucket is a Python list of (key, value) tuples.
Collisions are resolved by chaining, and average search time is
proportional to O(N / M) where:
β’ ``N`` = number of keyβvalue pairs
β’ ``M`` = number of buckets
This implementation is simple, predictable, and suitable for workloads where hash distribution is reasonably uniform.
Source code in src/alnoms/dsa/structures/separate_chaining_hash_st.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
__init__(m=997)
Initializes the hash table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
m
|
int
|
Number of buckets (chains). Defaults to 997, a prime number that helps reduce clustering. |
997
|
Attributes:
| Name | Type | Description |
|---|---|---|
_m |
int
|
Number of buckets. |
_n |
int
|
Number of stored keyβvalue pairs. |
_st |
List[List[Tuple[Any, Any]]]
|
Array of buckets. |
Source code in src/alnoms/dsa/structures/separate_chaining_hash_st.py
contains(key)
Checks whether the table contains the given key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to search for. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the key exists, otherwise False. |
Source code in src/alnoms/dsa/structures/separate_chaining_hash_st.py
delete(key)
Removes a key and its associated value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to remove. |
required |
Source code in src/alnoms/dsa/structures/separate_chaining_hash_st.py
get(key)
Retrieves the value associated with a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to search for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
Optional[Any]: The associated value if found, otherwise None. |
Source code in src/alnoms/dsa/structures/separate_chaining_hash_st.py
is_empty()
Checks whether the table contains any entries.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
int
|
True if the table is empty, otherwise False. |
keys()
Returns all keys stored in the table.
Returns:
| Type | Description |
|---|---|
List[Any]
|
List[Any]: A list containing all keys. |
Source code in src/alnoms/dsa/structures/separate_chaining_hash_st.py
put(key, val)
Inserts or updates a keyβvalue pair.
If the key already exists, its value is updated.
If val is None, the key is removed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key to insert. |
required |
val
|
Any
|
The value to associate with the key. |
required |
Source code in src/alnoms/dsa/structures/separate_chaining_hash_st.py
size()
Returns the number of keyβvalue pairs stored.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total number of entries. |
π΅οΈ Pattern Heuristics & Fixes (alnoms.patterns & alnoms.fixes)
The internal diagnostic rule engine that identifies computational bottlenecks.
π Detectors
Orchestrates AST analysis using the registered pattern detectors.
The engine loads all OSS detectors by default and conditionally extends the registry with PRO and ENTERPRISE detectors based on environment feature flags. Each detector is responsible for identifying a specific algorithmic antiβpattern.
This class exposes a single static method, analyze_code, which parses
the file into an AST and dispatches it to all registered detectors.
Source code in src/alnoms/patterns/heuristics.py
analyze_code(path)
staticmethod
Analyze a Python file using all registered pattern detectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the Python source file. |
required |
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: A flat list of findings from all detectors. Each finding is a dictionary containing detectorβspecific metadata such as: - "function": Function where the issue occurs - "pattern_id": Identifier of the detector - "issue": Description of the antiβpattern - "line": Line number of the issue - Additional detectorβspecific fields |
Notes
- Empty files return an empty list.
- Syntax errors or unexpected exceptions are captured and returned as a single fileβlevel finding rather than raising an exception.
Source code in src/alnoms/patterns/heuristics.py
Bases: PatternDetector
Detects nested loops and classifies their algorithmic intent.
This detector identifies functions containing nested for or while
loops and applies lightweight heuristics to infer the likely purpose
of the nested structure. The intent classification enables downstream
fixers to provide contextβaware remediation strategies.
Supported intent categories
β’ membership β equality checks, membership tests, pairwise scans β’ sorting β range(len(...)) patterns resembling selection/bubble sort β’ dfs β nested iteration over adjacency lists or graph structures β’ generic β fallback for unclassified quadratic scans
Source code in src/alnoms/patterns/nested_loops.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
detect(tree)
Detects nested loops within function bodies.
Traverses the AST to locate functions containing nested for or
while loops. When a nested loop is found, the detector assigns
an intent classification and records a single finding per function
to avoid noise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
AST
|
The parsed AST of the module being analyzed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: A list of findings, where each finding |
|
includes |
List[Dict[str, Any]]
|
|
Source code in src/alnoms/patterns/nested_loops.py
Bases: PatternDetector
Detect inefficient membership tests inside loops.
This detector flags occurrences of:
- `x in some_list`
- `x not in some_list`
- membership checks on literal lists/tuples
- membership checks on variables that are likely lists
When these appear inside loops, they create a hidden O(NΒ²) pattern due to
repeated linear scans. The detector uses heuristics to avoid false positives
on safe containers such as sets, dicts, ranges, and variables whose names
imply O(1) lookup semantics (e.g., visited, cache, lookup).
Attributes:
| Name | Type | Description |
|---|---|---|
SAFE_CONTAINER_HINTS |
set[str]
|
Variableβname substrings that imply O(1) membership semantics. |
Source code in src/alnoms/patterns/inefficient_membership.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | |
detect(tree)
Analyze the AST and flag inefficient membership tests inside loops.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
AST
|
Parsed AST of the target Python file. |
required |
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: A list of findings. Each finding includes: - "function": Function where the issue occurs - "pattern_id": Identifier for this detector - "issue": Description of the membership test - "complexity": Estimated complexity impact - "suggestion": Recommended remediation - "line": Line number of the issue |
Notes
- Literal lists/tuples of size β€ 3 are ignored as they are cheap.
- Safe containers (set/dict/range) are skipped.
- Variable names are heuristically classified for safety.
Source code in src/alnoms/patterns/inefficient_membership.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | |
Bases: PatternDetector
Detect potentially expensive function calls inside loops.
This detector walks the AST of each function and inspects all for and
while loops. Any function call inside a loop that is not part of the
SAFE_CALLS whitelist is flagged as a potential performance risk.
The whitelist includes:
- Common O(1) builtβins (
len,range,int, etc.) - Common O(1) container methods (
append,pop,get, etc.) - Sorting and I/O calls, which are handled by dedicated detectors
Attributes:
| Name | Type | Description |
|---|---|---|
SAFE_CALLS |
set[str]
|
Set of known O(1) or trivial operations that should not be flagged. |
Source code in src/alnoms/patterns/expensive_calls.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
detect(tree)
Analyze the AST and flag nonβwhitelisted calls inside loops.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
AST
|
Parsed AST of the target Python file. |
required |
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: A list of findings. Each finding includes: - "function": Name of the function containing the loop. - "pattern_id": Identifier for this detector. - "issue": Description of the detected call. - "complexity": Estimated complexity impact. - "suggestion": Recommended remediation. - "line": Line number of the call. |
Notes
- Only explicit
ast.Callnodes insidefor/whileloops are inspected. - Calls to safe O(1) operations are ignored.
- Sorting and I/O calls are delegated to other detectors.
Source code in src/alnoms/patterns/expensive_calls.py
Bases: PatternDetector
Detect highβfrequency I/O operations inside loops.
This detector walks the AST of each function and inspects all for and
while loops. Any call to open, read, or write inside a loop is
flagged as a performance risk due to:
- Excessive system calls
- Kernel context switching
- Disk or network latency
- Reduced throughput compared to buffered operations
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier for this detector. |
name |
str
|
Humanβreadable name for reporting. |
description |
str
|
Short description of the detector's purpose. |
Source code in src/alnoms/patterns/high_freq_io.py
detect(tree)
Analyze the AST and flag I/O operations inside loops.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
AST
|
Parsed AST of the target Python file. |
required |
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: A list of findings. Each finding includes: - "function": Name of the function containing the loop. - "pattern_id": Identifier for this detector. - "issue": Description of the detected I/O call. - "complexity": Qualitative complexity impact. - "suggestion": Recommended remediation. - "line": Line number of the call. |
Notes
- Only explicit
ast.Callnodes insidefor/whileloops are inspected. - This detector focuses on file and network I/O primitives.
- Buffered or batched I/O is recommended for performance.
Source code in src/alnoms/patterns/high_freq_io.py
Bases: PatternDetector
Detects in-place string/list concatenation inside loops.
This detector identifies patterns where += or *= are used on
potentially non-numeric variables inside for or while loops.
Such operations can trigger repeated memory reallocations, resulting
in O(N^2) scaling.
The detector includes heuristics to avoid false positives on numeric accumulation patterns (e.g., counters, totals, index updates).
Source code in src/alnoms/patterns/inplace_concat.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | |
detect(tree)
Detects in-place concatenation patterns inside loops.
Traverses the AST to find augmented assignments (+=, *=) that
occur within for or while loops. The detector filters out
numeric accumulation patterns and flags only those operations that
are likely to cause O(N^2) memory behavior due to repeated
reallocation of strings or lists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
AST
|
The parsed AST of the target Python module or function. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: A list of findings, where each finding |
|
includes |
List[Dict[str, Any]]
|
|
Source code in src/alnoms/patterns/inplace_concat.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | |
Bases: PatternDetector
Detects repeated sorting operations executed inside loops.
This detector inspects loop bodies for calls to Python's builtβin
sorting mechanisms (sorted() or list .sort()). When these calls
appear inside for or while loops, they can introduce
O(N^2 log N) behavior due to repeated sorting of the same or similar
data structures.
Sorting is typically intended to be performed once before iteration, or once after data collection, rather than on every loop iteration.
Source code in src/alnoms/patterns/redundant_sort.py
detect(tree)
Detects sorting calls (sort, sorted) inside loop bodies.
Traverses the AST to locate function definitions and inspects all nested loops for calls to Python's standard sorting functions. When found, the detector records a finding indicating that sorting should be moved outside the loop to avoid repeated O(N log N) operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
AST
|
The parsed AST of the module being analyzed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: A list of findings, where each finding |
|
includes |
List[Dict[str, Any]]
|
|
Source code in src/alnoms/patterns/redundant_sort.py
π Fixers
Bases: Fixer
Remediation strategy for nested loop patterns.
This fixer provides intentβaware remediation for nested loops, distinguishing between cubic patterns (e.g., matrix multiplication) and quadratic patterns such as membership scans, manual sorting, and DFSβlike adjacency traversal. Recommendations include algorithmic redesign, vectorization, hashing, and use of efficient data structures.
Attributes:
| Name | Type | Description |
|---|---|---|
pattern_id |
str
|
Identifier for the associated detector pattern. |
Source code in src/alnoms/fixes/nested_loops_fixer.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | |
cost_estimate(finding, detected_complexity='Unknown')
Provides a qualitative estimate of the complexity improvement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
finding
|
Dict
|
The detector finding associated with the issue. |
required |
detected_complexity
|
str
|
The complexity classification. |
'Unknown'
|
Returns:
| Type | Description |
|---|---|
|
Dict[str, str]: A dictionary describing expected improvements |
|
|
in time and memory complexity for cubic and quadratic cases. |
Source code in src/alnoms/fixes/nested_loops_fixer.py
explain(finding, detected_complexity='Unknown')
Provides a humanβreadable explanation of the nested loop issue.
This method generates intentβaware explanations for nested loops, distinguishing between cubic and quadratic patterns. It also provides domainβspecific guidance for matrix multiplication, membership scans, sortingβlike routines, and DFSβstyle traversal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
finding
|
Dict
|
The detector finding describing the nested loop. |
required |
detected_complexity
|
str
|
Static or empirical complexity. |
'Unknown'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
A narrative explanation describing the issue and the |
|
|
recommended remediation strategy. |
Source code in src/alnoms/fixes/nested_loops_fixer.py
snippet_before_after(finding, detected_complexity='Unknown')
Returns before/after code snippets illustrating the fix.
Snippets are intentβaware and tailored to the specific nested loop pattern detected. Cubic patterns receive vectorization or pruning guidance, while quadratic patterns receive hashing, sorting, or DFSβrelated improvements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
finding
|
Dict
|
The detector finding describing the nested loop. |
required |
detected_complexity
|
str
|
Complexity classification. |
'Unknown'
|
Returns:
| Type | Description |
|---|---|
|
Dict[str, str]: A dictionary containing:
- |
Source code in src/alnoms/fixes/nested_loops_fixer.py
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
Bases: Fixer
Remediation strategy for inefficient membership tests inside loops.
This fixer addresses patterns where membership checks such as
x in list or x in tuple occur inside a loop. These operations
are O(N) per lookup, leading to accidental O(N*M) or O(NΒ²) behavior.
The recommended remediation is to convert the container to a set
to achieve O(1) averageβcase membership checks.
Attributes:
| Name | Type | Description |
|---|---|---|
pattern_id |
str
|
Identifier for the associated detector pattern. |
Source code in src/alnoms/fixes/inefficient_membership_fixer.py
cost_estimate(finding, detected_complexity='Unknown')
Provides a qualitative estimate of the complexity improvement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
finding
|
Dict
|
The detector finding associated with the issue. |
required |
detected_complexity
|
str
|
The complexity classification. |
'Unknown'
|
Returns:
| Type | Description |
|---|---|
|
Dict[str, str]: A dictionary describing expected improvements |
|
|
in time and memory complexity. Converting to a set reduces |
|
|
repeated O(N) scans to O(1) lookups. |
Source code in src/alnoms/fixes/inefficient_membership_fixer.py
explain(finding, detected_complexity='Unknown')
Provides a humanβreadable explanation of the optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
finding
|
Dict
|
The detector finding describing the membership pattern. |
required |
detected_complexity
|
str
|
The static or empirical complexity associated with the antiβpattern. |
'Unknown'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
A narrative explanation describing why listβbased membership |
|
|
checks inside loops are slow and how converting to a set improves |
||
|
performance. |
Source code in src/alnoms/fixes/inefficient_membership_fixer.py
snippet_before_after(finding, detected_complexity='Unknown')
Returns before/after code snippets illustrating the fix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
finding
|
Dict
|
The detector output for the inefficient membership test. |
required |
detected_complexity
|
str
|
Complexity classification used to contextualize the snippet. |
'Unknown'
|
Returns:
| Type | Description |
|---|---|
|
Dict[str, str]: A dictionary containing:
- |
Source code in src/alnoms/fixes/inefficient_membership_fixer.py
π‘οΈ Pre-Deployment Governance (CLI)
Provides the command-line interface for the Alnoms performance intelligence system. The CLI orchestrates static AST analysis, prescriptive remediation suggestions, dynamic profiling, and empirical doubling tests to detect performance bottlenecks before production.
Features
- CI/CD Ready: Supports raw and pretty JSON outputs for automation pipelines.
- Static Analysis: Detects inefficient loops, API calls, and performance traps.
- Prescriptive Suggestions: Recommends O(1) fixes and optimized patterns.
- Empirical Analysis: Integrates with Arprax Profiler for Big-O scaling analysis.
PerformanceCLI
Performance Intelligence CLI for complexity analysis and profiling.
Acts as the primary entrypoint for the Alnoms performance intelligence system. Provides a terminal interface for static analysis, dynamic profiling, empirical scaling tests, and structured performance reporting. Designed for both human-readable output and CI/CD automation.
Source code in src/alnoms/cli.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | |
main()
staticmethod
Primary entry point for the Alnoms Command-Line Interface.
Configures the argument parser and routes execution based on the selected
subcommand. Supports two primary modes:
1. analyze: Human-readable performance reporting with deep profiling options.
2. ci: Headless execution mode that accepts multiple files, outputs strict
JSON, and enforces Big-O complexity guardrails via system exit codes.
Raises:
| Type | Description |
|---|---|
SystemExit
|
|
Source code in src/alnoms/cli.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | |
print_report(result)
staticmethod
Renders a full performance intelligence report in human-readable format.
This method produces a structured analysis report that includes detected performance patterns, static diagnostics, dynamic profiling bottlenecks, empirical scaling analysis, performance verdict, and simulated fixes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
dict
|
Output from |
required |
Source code in src/alnoms/cli.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |