High-Performance Algebraic Loop Lifting & Exact Rational Recurrence Engine for Python and C
Traditional compilers, runtimes, and JIT engines (such as GCC, Clang, PyPy, or Numba) treat loops as repetitive control-flow sequences, executing instructions step-by-step:
When
- State Transition Formulation: It statically inspects the loop body and formulates its mathematical state transition matrix:
-
Closed-Form Solution: It solves the recurrence system in closed form, reducing execution time from
$\mathcal{O}(N)$ to$\mathcal{O}(1)$ (for scalar/periodic/telescoping series) or$\mathcal{O}(\log N)$ (via fast binary matrix exponentiation).
Strilight does not pretend to introduce esoteric magic; it is fundamentally a developer quality-of-life tool.
In physical modeling, scientific computing, and numerical simulation, engineers frequently face a frustrating dilemma:
- Readable Code: Natural, expressive equations that mirror textbook physics, but execute sluggishly when iterated millions of times.
- Hand-Optimized Code: Convoluted, manually unrolled loops and obscure arithmetic shortcuts that run fast, but are brittle, difficult to debug, and obscure the underlying physics.
Strilight resolves this dilemma. You write the physical or mathematical concept in whatever straightforward, natural syntax you prefer. Strilight inspects your loop structure, derives the exact closed-form recurrence formulas, and accelerates execution behind the scenes—preserving complete readability and simplicity in your codebase.
Floating-point arithmetic introduces cumulative truncation errors (
- Multipliers and offsets are modeled as canonical fractions (
$\frac{p}{q}$ ). - Emits double-precision kernels in C and exact
Fractionrepresentations in Python, guaranteeing 100% bit-exact mathematical parity.
Variables that mutually depend on each other (e.g., physical simulations where position depends on velocity and velocity depends on acceleration) are automatically extracted into a Variable Coupling Matrix (
Decorating any standard Python function with @accelerate executes an automated pipeline at function definition time (zero per-call runtime analysis overhead):
-
AST Extraction: Inspects the function AST, identifies
forloop constructs, and extracts induction variables. - Closed-Form Synthesis: Translates the loop into equivalent closed-form recurrence models or binary matrix exponentiation kernels.
-
In-Place Splicing: Replaces the loop AST nodes in-place, compiles the callable into memory, and injects runtime globals (
Fraction,math) without polluting module namespaces. -
Contract Reflection: Attaches
_loop_summaryand_invariant_contractto the compiled function object, enabling downstream compilers and verification tools to inspect the underlying transition matrix$\mathbf{A}$ . - Graceful Fallback: If non-linear indexing or unsupported dynamic calls are encountered, Strilight emits a diagnostic warning and cleanly falls back to native execution without crashing.
from strilight import accelerate
@accelerate
def compute_simulation(steps: int) -> int:
acc = 0
for i in range(steps):
acc += (i * 3) + 7
return acc
# Executes in O(1) time (~0.001 ms even if steps = 100,000,000)
result = compute_simulation(100_000_000)Unlike Python's dynamic reflection, C code transformations in Strilight strictly follow an explicit Developer-Contract Model via OpenMP-style pragma directives. The engine never mutates C source code implicitly; transformations occur solely when directed by explicit developer contract clauses (contract, target, include, model):
-
#pragma strilight accelerate: Explicitly authorizes Strilight to lift the annotated Cforloop into an equivalent closed-form mathematical expression. -
#pragma strilight fuse: Explicit developer directive instructing Strilight to fuse designated adjacent loops sharing identical iteration domains into a unified$\mathcal{O}(\log N)$ binary matrix recurrence kernel.
// Example of contract-guided multi-loop fusion via developer directive
int simulate_motion(int n) {
int pos = 0, vel = 10;
#pragma strilight fuse
for (int i = 0; i < n; i++) {
pos += vel;
}
for (int i = 0; i < n; i++) {
vel += 2;
}
return pos;
}Numerical simulations frequently define parameters in separate header files or configuration modules. Strilight's CrossFileResolver:
- Statically traces local module imports and C
#include/#definedirectives. - Evaluates literal constant expressions (e.g.
SOLAR_MASS = 4 * PI * PI) across files via AST evaluation without executing arbitrary runtime code or using unsafeeval.
-
Cyclic Array Lookup: Lifts cyclic table lookups (
table[i % P]) into precomputed prefix-sum closed formulas in$\mathcal{O}(1)$ . -
In-Place Array Slice Mutation: Classifies constant fills and arithmetic progressions, synthesizing optimal hardware
memsetcalls or vector slice assignments (arr[:N] = ...).
In mechanical and astrophysical simulations (e.g.,
- Analytical Trajectory Synthesis: When Strilight identifies that a particle or celestial body is following an unperturbed gravitational or linear trajectory, it collapses the iterative time-stepping loop into the minimal possible mathematical operations (analytical Keplerian/harmonic orbital formulation)—without sacrificing coordinate precision.
-
Transition to Complex Events: When complex events occur (discrete collisions, boundary wall impacts, or irregular multi-body couplings), execution transitions into specialized collision coupling matrices (
$\mathbf{A}$ ) or localized simulation stages. -
Zero Code Risk: Strilight is completely non-invasive. In Python, it is a single
@acceleratedecorator; in C, it is a standard#pragma. You can add or remove it at any time without altering your algorithm or business logic. - Decisive Graceful Fallback: If Strilight encounters a loop with unstructured side-effects, unknown external calls, or non-affine dynamics, it decisively and cleanly halts acceleration attempts and falls back to native execution. Your program never crashes.
Modern AI coding assistants (such as Claude, Gemini, GPT, or Jules) excel when operating over algebraic formulas and closed-form equations. Strilight makes it straightforward for developers and AI agents to inspect the synthesized code and mathematical contracts directly:
from strilight import accelerate
@accelerate
def compute_energy(steps: int) -> int:
total = 0
for i in range(steps):
total += 15
return total
# Execute once to trigger definition-time synthesis
result = compute_energy(100)
# Inspect the underlying mathematical contract:
summary = compute_energy._loop_summary
print("Extracted Induction Formulas:", summary.to_induction_formulas())
print("Invariant Contract:", compute_energy._invariant_contract.to_dict())You can pass C source code directly to accelerate_c_source to generate inspectable, human-readable accelerated C kernels:
import strilight as sl
c_source = """
long long simulate(void) {
long long total = 0;
#pragma strilight accelerate target(total)
for (int i = 0; i < 1000000; i++) {
total += 42;
}
return total;
}
"""
accelerated_c = sl.accelerate_c_source(c_source)
print(accelerated_c)
# Emits: total += (42LL * 1000000);We believe in engineering transparency:
-
No Blanket Guarantees: Strilight does not claim that every arbitrary, unconstrained loop will magically become
$\mathcal{O}(1)$ . Highly irregular pointer chasing, arbitrary dynamic I/O, or non-algebraic external function calls are fundamentally non-reducible. -
Predictable Success: For structured loops—scalar reductions, multi-variable linear couplings, cyclic arrays, and contract-guided loops—Strilight reliably succeeds. In C, providing explicit pragma clauses (
target,include,model) provides deterministic transformation guarantees.
Evaluated across high-iteration numerical loops, comparing native execution against Strilight acceleration:
| Benchmark Scenario | Iterations ( |
Native Baseline | Strilight Accelerated | Measured Speedup | Precision Fidelity |
|---|---|---|---|---|---|
| Coupled 4x4 Linear System (Python) | 100% Bit-Exact | ||||
| Coupled 4x4 Linear System (GCC -O2) | 100% Bit-Exact | ||||
| Cyclic Array Lookup Summation | 100% Bit-Exact | ||||
| Planetary N-Body Celestial Mechanics | Analytical Orbit Parity |
flowchart TD
SRC["Source Code (Python / C)"] --> LIFTER["SourceLifter: AST & Pragma Parser"]
LIFTER --> RESOLV["CrossFileResolver: Static Import Resolution"]
RESOLV --> VSA["Algebraic Induction Engine: models.py"]
VSA --> MATRIX["VariableCouplingMatrix: System Transition Matrix A"]
VSA --> QFIELD["Exact Rational Domain over Q: AffineExpr"]
REDUCE --> CODEGEN["CodeGenerator: C / Python Synthesis"]
VSA --> REDUCE["Schur Reduction & Block-Diagonal Decomposition"]
CODEGEN --> OUT["O(1) / O(log N) Executable Kernel"]
Strilight addresses computational bottlenecks across scientific, engineering, and financial domains:
- Domain: N-Body celestial mechanics, orbital state propagation, and multi-particle kinematic cascades.
-
Advantage: Bypasses iterative
$\mathcal{O}(N)$ numerical time-stepping. Evaluates the state vector at arbitrary future epoch$T$ directly in$\mathcal{O}(1)$ or$\mathcal{O}(\log N)$ , eliminating cumulative numerical drift via exact rational arithmetic over$\mathbb{Q}$ .
- Domain: Compound interest accrual streams, annuities, fixed-income modeling, and multi-period asset depreciation.
- Advantage: Replaces multi-thousand-step simulation loops with exact closed-form evaluations in microseconds. Guarantees 100% bit-exact rational precision, eliminating floating-point rounding discrepancies prohibited under financial regulations.
- Domain: Particle emitters, projectile trajectories, and continuous camera animations.
- Advantage: Offloads heavy sequential loops from the CPU during real-time 60/120 FPS frame cycles, collapsing iterative accumulator passes into single-cycle algebraic evaluations executing in sub-nanoseconds.
- Domain: Resource-constrained microcontrollers (ARM Cortex-M, RISC-V, ESP32) operating under strict power and clock limitations.
-
Advantage: Collapsing billion-iteration cycles into an instantaneous
$\mathcal{O}(1)$ arithmetic statement delivers substantial energy savings and guarantees bounded, deterministic execution deadlines.
- Domain: Invariant inference, symbolic execution, and automated theorem proving (SMT/Z3).
- Advantage: Synthesizes formal mathematical induction contracts (
LoopInvariantContract) without memory-intensive loop unrolling.
pip install strilightgit clone https://github.com/asama7706r-ui/strilight.git
cd strilight
pip install -e .Execute the test suite and reproducible benchmarks:
# Run the 60-test unit and induction verification suite:
pytest
# Python recurrence acceleration:
python examples/01_python_recurrence_acceleration.py
# Jovian planetary N-body celestial simulation benchmark:
python examples/02_nbody_simulation_benchmark.py
# Coupled 4x4 linear matrix recurrence benchmark (O(N) -> O(log N) -> O(1)):
python examples/03_coupled_matrix_benchmark.py
# C Developer Contract & pragma acceleration suite:
python examples/c/run_c_acceleration.pyThe core mathematical engine of Strilight is 100% open source under the GNU GPLv3 license.
We warmly welcome contributions from the global compiler, scientific computing, and performance engineering communities:
- Multi-Language Adapters: Adding frontends for other compiled or dynamic languages (such as Rust, Julia, Fortran, or C++).
- Recurrence Solvers & Models: Expanding the algebraic model library with non-linear perturbation solvers, advanced geometric transformations, or specialized symbolic matrix decomposition algorithms.
- Component Refinement: Enhancing AST pattern matchers, developer pragmas, and developer experience tooling.
If you are interested in contributing, feel free to open an issue or submit a pull request on GitHub!
Strilight is released under a Dual-Licensing Model:
- Open Source (GNU GPLv3): Free for academic research, open-source projects, and personal experimentation.
- Commercial License: For integration into proprietary commercial products or enterprise pipelines without GPL copyleft obligations.
Contact: asama7706r@gmail.com